Monday, December 26, 2011

how to write to a text file in c#

In .net we have a various classes to create, write and perform some operations on a text file which are file .Here we are using create() method to create a text file and using some classes to reading and writing text files those are TextReader,StreamReader,StreamWriter,TextWriter classes.These are abstract classes .Here i have taken a logfilepath which is the physical path of the text file.If the file is existing in path then we will write message into this text file.If the file is not existing in the path then we will create a file in this path and write a message into it
Code Behind:
public static string path = AppDomain.CurrentDomain.BaseDirectory;
public static string LogfilePath = path + @"archives\error.txt";
public static void WriteError(string msg)
 {
  try
   {
    if (!File.Exists(LogfilePath))
       {
       File.Create(LogfilePath).Close();
       }
    using (StreamWriter w = File.AppendText(LogfilePath))
       {
        w.WriteLine("\r\nLog Entry : ");
        w.WriteLine("{0}",DateTime.Now.ToString(CultureInfo.InvariantCulture));
        string err = "Error Message:" + msg;
        w.WriteLine(err);
        w.Flush();
        w.Close();
       }
   }

No comments:

Bel