Showing posts with label File. Show all posts

[C#] Write Text File

This function creates a text file when it runs. In the directory where you give in filePath and strContent you want to write. If you view the contents of this file, you'll see the following textual representation of the date and time when the program last ran.

void WriteTextFile(string filePath, string strContent)
{
    StreamWriter sW = new StreamWriter(filePath);
    sW.Write(strContent);           // Not line breaks
    //sW.WriteLine(strContent);     // Write and line breaks
    sW.Write(DateTime.Now);         // Write Date

    // Flush and Close
    sW.Close();
}

[C#] Read Text file Line by Line

Here is the code to read a text file from disk one line at a time into a string.  This code ensures the file exists and properly closes the file if an exception occurs.
Use these namespaces

using System;
using System.IO;

// Use this function

        private void ReadTextFile(string filePath)
        {
            // initialize line to fill content each line
            string line;
            if (File.Exists(filePath))      // Check existence
            {
                StreamReader file = null;   // initialize Reader
                try
                {
                    file = new StreamReader(filePath);
                    // Read line by line, stop if null.
                    while ((line = file.ReadLine()) != null)   
                    {
                        // === Use each line ===
                        Console.WriteLine(line);
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.ToString());
                }
                finally
                {
                    if (file != null)
                        file.Close();
                }
            }
        }