Disposing File Object Properly
Ok so heres the thing. When ever a trigger is hit i append my logs in a
specific folder. The code works fine and it appends it correctly but if i
try to manually delete the folder from the desktop its giving a "The
action cannot be completed cause the folder/file is open in another
program";
i guess im not disposing it right but i dont know where i missed it. I
know its the folder that is attached to the process cause i tried to
delete the .log file inside and it allowed me.
private void LogEvent(string filename,bool AppendTxt,string msg)
{
string sLogFormat = DateTime.Now.ToShortDateString().ToString() +
" " + DateTime.Now.ToLongTimeString().ToString() + " ==> ";
msg = sLogFormat + msg;
// create directory
if
(System.IO.Directory.Exists("C:\\Users\\DT-Npax\\Desktop\\LOGS1")
!= true)
{
Directory.CreateDirectory("C:\\Users\\DT-Npax\\Desktop\\LOGS1");
}
string dailyLog = "C:\\Users\\DT-Npax\\Desktop\\LOGS1" + "\\" +
filename + ".log";
FileStream FS = null;
//write or append txt
if (!AppendTxt)
{
if (File.Exists(dailyLog))
{
File.Delete(dailyLog);
}
using (FS = File.Create(dailyLog)) { }
FS.Close();
StreamWriter TXT_WRITE = new StreamWriter(dailyLog);
TXT_WRITE.WriteLine(msg);
TXT_WRITE.Close();
}
else
{
if (!File.Exists(dailyLog))
{
using (FS = File.Create(dailyLog)) { }
FS.Close();
}
FileStream FSAppend = new FileStream(dailyLog,
FileMode.Append, FileAccess.Write);
StreamWriter TXT_WRITE = new StreamWriter(FSAppend);
TXT_WRITE.WriteLine(msg);
TXT_WRITE.Close();
FSAppend.Close();
}
}
No comments:
Post a Comment