Monday, September 21, 2009

Writing to the text file in C# or VB.net

As a programmer we always need to deal with writing/reading to/from text files, it could be anything from error log, some debugging messages etc.
Below is the code in C# and VB.Net which accepts a message to write and a file name and appends it to given file if exists, else it will create a file and writes to it with current time stamp.
-------------------------------------------C# Code--------------------------------------
using System.IO;
class FileOperations
{
public static void WriteToTextFile(string strMessageToWrite, string strFilePath)
{
StreamWriter objStreamWriter;
try
{
if (File.Exists(strFilePath) == false)
{
objStreamWriter = File.CreateText(strFilePath);
}
else
{
objStreamWriter = File.AppendText(strFilePath);
}
objStreamWriter.WriteLine(DateTime.Now.ToString() + ": " + strMessageToWrite);
objStreamWriter.Close();
}
catch (IOException IOExp)
{
throw IOExp;
}
catch (Exception Ex)
{
throw Ex;
}
}
}
-------------------------------------------VB.Net Code-----------------------------------------------
Imports System.IO
Public Class FileOperations
Public Sub WriteToTextFile(ByVal strMessageToWrite As String, ByVal strFilePath As String)
Dim objStreamWriter As StreamWriter
Try
If File.Exists(strFilePath) = False Then
objStreamWriter = File.CreateText(strFilePath)
Else
objStreamWriter = File.AppendText(strFilePath)
End If
objStreamWriter.WriteLine(Date.Now & ": " & strMessageToWrite)
objStreamWriter.Close()
Catch IOExp As IOException
Throw IOExp
Catch ex As Exception
Throw ex
End Try
End Sub
End Class
-----------------------------------------------------------------

No comments:

Post a Comment