如何在 Visual Studio 2017 中将数据 write/read 写入文件

How to write/read data to a file in Visual Studio 2017

我正在用 C# Universal 创建一个应用程序 Windows,我想知道如何将数据写入文件以便稍后可以从中读取数据。我正在考虑制作一个 class System.Serializable,然后将 class 的对象作为文件写入用户的设备,这样我就可以再次将这些文件作为对象读回,但我不知道怎么做。

使用Fileclass。它具有您需要的所有功能 - 打开文件、读取其内容、编辑、保存或删除。 来自 MSDN:

public static void Main()
{
    string path = @"c:\temp\MyTest.txt";
    if (!File.Exists(path))
    {
        // Create a file to write to.
        using (StreamWriter sw = File.CreateText(path))
        {
            sw.WriteLine("Hello");
            sw.WriteLine("And");
            sw.WriteLine("Welcome");
        }
    }

    // Open the file to read from.
    using (StreamReader sr = File.OpenText(path))
    {
        string s = "";
        while ((s = sr.ReadLine()) != null)
        {
            Console.WriteLine(s);
        }
    }
}

在 .NET 框架中,有一个名为 System.IO 的命名空间。

System.IO.StreamWriter writer = new System.IO.StreamWriter(filepath);

您可以使用 System.IO 命名空间中的 StreamWriter 来写入文件。构造函数只是将字符串变量传入要写入的文件的路径。然后你可以使用 StreamReader(像这样):

System.IO.StreamReader reader = new System.IO.StreamReader(filepath);

重新读回文件。

这是一个例子:

class Program
{
    [Serializable]
    public class MyClass
    {
        public string Property1{ get; set; }
        public string Property2 { get; set; }
    }

    static void Main(string[] args)
    {
        var item = new MyClass();
        item.Property1 = "value1";
        item.Property2 = "value2";

        // write to file
        FileStream s = new FileStream("myfile.bin", FileMode.Create);
        BinaryFormatter f = new BinaryFormatter();
        f.Serialize(s,item);
        s.Close();

        // read from file
        FileStream s2 = new FileStream("myfile.bin", FileMode.OpenOrCreate,FileAccess.Read);

        MyClass item2 = (MyClass)f.Deserialize(s2);
    }
}