Monday, November 6, 2017

Create/Save/Write/Append text in a txt file (c# / .NET)


Many requirements will come in application development where we have to create or update a text file for certain purpose. For example that may be a log file or any accumulative text files.

Here is a function which implements the code to create/save/write/append text in a text file. You can further modify the function or create a new one as per your need. You can pass texts and filepath as arguments and modify internal code based on your requirement.

       void MyFunction()
        {
            // path to your txt file
            string filePath = @"D:\myFile.txt";

            // if file does not exist, it will create a new file and dispose the resource used by stream
            if (!File.Exists(filePath))
            {
                File.Create(filePath).Dispose();
            }

            // instanciate a stream writer for the txt file.
            using (StreamWriter writer = File.AppendText(filePath))
            {
                // writes the line to the file and inserts a line break
                writer.WriteLine("I will insert a line break.");
                // writes the string to the stream
                writer.Write("I am written in a stream.");
                writer.Write("I am continued.");
                // NOTE : you can also write it asynchronously. check the functions in writer.
            }
        }

No comments:

Post a Comment