Saturday, June 21, 2008

file operation [C# VS2005]

Some notes about file operation that I have used before, including write file, listing file in directory, delete file. To use file/directory existing function don't forget to include System.IO

try
{
sPath = "C:\\TEMP";
if( Directory.Exists(sPath) )
{
string[] sFiles = Directory.GetFiles(sPath);
for (int i = 0; i < sFiles.Length; i++)
{
File.Delete(sFiles[i]);
}
}
else Console.WriteLine( sPath + " directory is not exist!");
}
catch (Exception ex)
{
Console.WriteLine( ex.Message );
}

Let say that I want to delete all files in a specified folder but excluding its sub folder, first I check whether the path is valid or not => Directory.Exists, if valid then next step is I populate all files in the directory => Directory.GetFiles, the last one is we iterate and delete all existing files in directory => File.Delete

try
{
string sErrLogPath = "C:\\TEMP";
string sErrMsg = "Error to be written...";
string sYear = DateTime.Now.Year.ToString();
string sMonth = DateTime.Now.Month.ToString("00");
string sDay = DateTime.Now.Day.ToString("00");
string sErrFilePath = sErrLogPath + "\\" + sYear + "_" + sMonth + "_" + sDay;
string sFileName;
if( !Directory.Exists( sErrFilePath ) )
{
Directory.CreateDirectory(sErrFilePath);
}
sFileName = "ErrLog" + DateTime.Now.Hour.ToString("00") +
DateTime.Now.Minute.ToString("00") + DateTime.Now.Second.ToString("00");
StreamWriter sw = new StreamWriter(sErrFilePath + "\\" + sFileName + ".txt", false);
sw.Write(sErrMsg);
sw.Close();
}
catch (Exception ex)
{
Console.WriteLine("Failed to write log file " + ex.Message);
}
Sometimes I want to make a note in a file for errors in my programs, so I just write the error message in file I created, rather than have to debug it first, quite helpful for me :P. In the code above I'm trying to make sub folder in C:\TEMP that contains my error message, the sub folder name format is YYYY_MM_DD. After that I create file for errors naming with ErrLog
hh_mm_ss

No comments: