Reading and Writing to a file text file in C#

Lets start by taking the below  code as an example:
  
private void WriteToAFile(){
            string data = “hi ! what’s up”;
            string path = “data.txt”;
            if (!File.Exists(path))
            {
                File.Create(path);
            }
            using (StreamWriter writer = new StreamWriter(path, append: true))
            {
                writer.WriteLine(data);
            }
}
Writing to a text file can be achieved by using StreamWriter class . To use this class we need to use System.IO namespace.
if we are writing to a file then exception might occur if the file doesn’t exists. So firstly we need to check if the File Exists. If it doesn’t exist we can create a file in the path specified.
Here in example I haven’t provided the fully qualified path like 
“C:UsersMypcprojectSample” absolute path 
but rather used relative path by providing only the file name.
The file will be created inside the bin folder either in debug or release depending on how you run.
Creating object of StreamWriter by passing path and true as  parameter.
Append mode opens file and moves pointer to the end of file, so the next thing you write will be appended else the existing data will be overwritten.
WriteLine method writes stream to the file with line terminator.
Similar Write method can be used to write string to the file.
there are several overloading methods to these stated methods.
   
Reading from a text file
Reading can be achieved by using StreamReader class.
below is the code example to read from an existing text file:

using (StreamReader sr = new StreamReader(path))
            {
                while ((line = sr.ReadLine()) != null)
                {
                    Console.WriteLine(line);
                }
            }

Leave a Reply

Your email address will not be published. Required fields are marked *