Easiest way to read from and write to files

后端 未结 12 1728
[愿得一人]
[愿得一人] 2020-11-22 08:04

There are a lot of different ways to read and write files (text files, not binary) in C#.

I just need something that is easy and uses the least amount of c

12条回答
  •  无人及你
    2020-11-22 08:34

    In addition to File.ReadAllText, File.ReadAllLines, and File.WriteAllText (and similar helpers from File class) shown in another answer you can use StreamWriter/StreamReader classes.

    Writing a text file:

    using(StreamWriter writetext = new StreamWriter("write.txt"))
    {
        writetext.WriteLine("writing in text file");
    }
    

    Reading a text file:

    using(StreamReader readtext = new StreamReader("readme.txt"))
    {
       string readText = readtext.ReadLine();
    }
    

    Notes:

    • You can use readtext.Dispose() instead of using, but it will not close file/reader/writer in case of exceptions
    • Be aware that relative path is relative to current working directory. You may want to use/construct absolute path.
    • Missing using/Close is very common reason of "why data is not written to file".

提交回复
热议问题