Contact Us

Scripts: C# :: File i/o operations :: Library Article #9

Developer's Section

Writing Data to a File in C#
By: Erobo Team Member

Hire a Developer for Related Work / Installation | $55 hr
Rating:  | Rate It:   
Average Votes: (3252)

Learn a simple technique to write data to a file using c#

In the example shown below, we create a StreamWriter object to write data to a file. To do this we call the method appendText which takes as input the path to the file. If the file does not exist, it will attempt to create it. Otherwise it will append a new line to the file.

 Code Snippet 1

//Namespaces used. Include at the top of your script

using System;
using System.Data;
using System.IO;
using System.Configuration;

public static void writeDataToFile(string Msg)

  StreamWriter sw = null;
    string path;

    path = "C:\\Temp\\"; //' Or from App.Config ConfigurationSettings.AppSettings["LogFolder"];

    if (path == null || path == "")
      path = System.IO.Path.GetDirectoryName( 
      System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase );

      //this returns URI encoded file path, take out the file:\ part of it in front
      path = path.Replace("file:\\","");

      //do not write anything in the \bin directory, use its parent dir
      if (path.EndsWith("\\bin") || path.EndsWith("bin\\") )
        path = path.Substring(0, path.Length-4); 

    string today = 
    DateTime.Now.Year.ToString().Substring(2,2) + 
    DateTime.Now.Month.ToString().PadLeft(2,'0') + 

    //string ASSEMBLY_NAME = System.Reflection.Assembly.GetExecutingAssembly().GetName().Name;
    string ASSEMBLY_NAME = System.Threading.Thread.CurrentThread.Name;

    string _logFile = path + "\\" + ASSEMBLY_NAME + "_Informational_"+today+".log";

    sw = File.AppendText(_logFile); 
    sw.WriteLine(DateTime.Now.ToString() + "MACHINE="+ System.Net.Dns.GetHostName()+"-> " + Msg);
  catch(Exception ex)
    ex = ex;
   if (sw != null) sw.Close();

See other Scripts in File i/o operations

Submit Your Scripts:

System Message:
  • Your C# script has been sent. Please allow 48 hours for processing.

If you would like to have your Javascripts published in this section please fill out
the form below:
*Your Name or Username:
Home Town:
*Description and Code:
*Enter Code shown
to the right:

[ Refresh Image ]