Products
Services
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: (3433)
Favorites:

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;
  try
  {
    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') + 
    DateTime.Now.Day.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);
    sw.Close();
  } 
  catch(Exception ex)
  {
    ex = ex;
  }
  finally
  {
   if (sw != null) sw.Close();
  }
}


See other Scripts in File I/O Operations

Submit Your Scripts:

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

[ Refresh Image ]