Open and Append to a Log File : Text File Read Write « File Stream « C# / C Sharp






Open and Append to a Log File

   
using System;
using System.IO;

class DirAppend
{
    public static void Main()
    {
        using (StreamWriter w = File.AppendText("log.txt"))
        {
            Log("Test1", w);
            Log("Test2", w);
            w.Close();
        }
        using (StreamReader r = File.OpenText("log.txt"))
        {
            DumpLog(r);
        }
    }

    public static void Log(string logMessage, TextWriter w)
    {
        w.WriteLine("{0} {1}", DateTime.Now.ToLongTimeString(),DateTime.Now.ToLongDateString());
        w.WriteLine("  :{0}", logMessage);
        w.Flush();
    }

    public static void DumpLog(StreamReader r)
    {
        string line;
        while ((line = r.ReadLine()) != null)
        {
            Console.WriteLine(line);
        }
        r.Close();
    }
}

   
    
    
  








Related examples in the same category

1.Read and Write a Text File
2.Read text file line by line
3.Read ASCII string from byte bufferRead ASCII string from byte buffer
4.Reads and displays bytes until end-of-fileReads and displays bytes until end-of-file
5.Write string to a text file
6.Read whole text file to the end
7.Read text file line by line with exception catch
8.Text file Write with format and write boolean value to a text file
9.Action Text Reader Line
10.Read and Write to a Newly Created Data File
11.Read Text from a File
12.Read text file with File.OpenText
13.Write Text to a File
14.Read a text file and obtain it's contents.
15.Reads text from a file.
16.Saves the text to a file.
17.Read Text File From Ressource
18.Create a large file of 100 lines to upload
19.Creates or opens a file for writing and writes text to it.
20.Returns the raw number of the current line count.
21.Returns the zero-based line number where source appears in target.
22.Returns the number of lines appearing in target where a line is counted as a '\n'