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 code, because I am going to be working with files a lot in my project. I only need something for string
since all I need is to read and write string
s.
Use File.ReadAllText and File.WriteAllText.
It could not be simpler...
MSDN examples:
In addition to
File.ReadAllText
,File.ReadAllLines
, andFile.WriteAllText
(and similar helpers fromFile
class) shown in another answer you can useStreamWriter
/StreamReader
classes.Writing a text file:
Reading a text file:
Notes:
readtext.Close()
instead ofusing
, but it will not close file/reader/writer in case of exceptionsusing
/Close
is very common reason of "why data is not written to file".You're looking for the
File
,StreamWriter
, andStreamReader
classes.Simple, easy and also disposes/cleans up the object once you are done with it.
The easiest way to read from a file and write to a file:
@AlexeiLevenkov pointed me at another "easiest way" namely the extension method. It takes just a little coding, then provides the absolute easiest way to read/write, plus it offers the flexibility to create variations according to your personal needs. Here is a complete example:
This defines the extension method on the
string
type. Note that the only thing that really matters is the function argument with extra keywordthis
, that makes it refer to the object that the method is attached to. The namespace and class declarations are optional.This is how to use the
string extension method
, note that it refers automagically to theclass Strings
:I would never have found this myself, but it works great, so I wanted to share this. Have fun!