Wednesday, May 20, 2009

Saving,Reading,Writing and Appending a text file [File Handling]

In some scenerio,we need to create file in same diroctory where application or exe file already exists.below given code help to create a new file with new name.File name is generated by date and time concatenation procedure.

/*To create TEXT file in same diroctory and return file name for further use.
This function "WriteToFile" generate a new unique file name with the help of current date and current time concatination.and save this file to given folder name.*/

private static void WriteToFile(out string _FileName)
{
StreamWriter SW = null;
string DirRoot = Directory.GetDirectoryRoot(Directory.GetCurrentDirectory());
string[] DirDetail = getLogFilePath();
string LogFilePath = DirDetail[0];
foreach (string strDir in Directory.GetLogicalDrives())
{
if (strDir == DirRoot)
{
string FolderName = DirDetail[1];
DirectoryInfo dirInfo = new DirectoryInfo(LogFilePath + FolderName);
if (!dirInfo.Exists)
dirInfo.Create();
}
}
_FileName = "LogFile" + DateTime.Now.Date.Month.ToString() + DateTime.Now.Date.Day.ToString() + DateTime.Now.Date.Year.ToString() + DateTime.Now.TimeOfDay.Hours.ToString() + DateTime.Now.TimeOfDay.Minutes.ToString() + DateTime.Now.TimeOfDay.Seconds.ToString();
try
{
SW = File.CreateText(LogFilePath + DirDetail[1] + _FileName + ".txt");
}
catch (Exception ex)
{
throw new ApplicationException(ex.Message);
}
if (SW != null)
SW.Close();
}

/*To Append Text into same file
below fnction "AppendToFile" use to append text value in existing file in each call.*/

private static void AppendToFile(string filename, string Msg)
{
string[] DirDetail = getLogFilePath();
string LogFilePath = DirDetail[0];
StreamWriter SW = null;
try
{
SW = File.AppendText(LogFilePath + DirDetail[1] + filename + ".txt");
}
catch (Exception ex)
{
throw new ApplicationException(ex.Message);
}
if (SW != null)
{
SW.WriteLine(Msg);
SW.Close();
}
}

/*To get same diroctory path where file will be save.
This function will generate new default folder (if and only if default folder does not exists).and return this folder nameas well as folder path.*/

private static string[] getLogFilePath()
{
string DirRoot = Directory.GetDirectoryRoot(Directory.GetCurrentDirectory());
string LogFilePath = string.Empty;
string FolderName = "Logs\\";
LogFilePath = Directory.GetCurrentDirectory() + "\\";
string[] DirDetail = new string[2];
DirDetail[0] = LogFilePath;
DirDetail[1] = FolderName;
return DirDetail;
}

No comments:

Post a Comment