log file

M

Mullin Yu

is the following capable of restricting more than one program writing error
log to file? in the past, i got error stating the log file is currently
opened by another process.

private void LogError2File(string errorMessage, string LogFilePath)

{

FileInfo oFileInfo = new FileInfo(LogFilePath);

DirectoryInfo oDirInfo = new DirectoryInfo(oFileInfo.DirectoryName);


if(!oDirInfo.Exists)

oDirInfo.Create();

if(!oFileInfo.Exists)

oFileInfo.Create();


//StreamWriter w = File.AppendText(LogFilePath);

//FileStream fs = new FileStream(oFileInfo.FullName, FileMode.Open,
FileAccess.Write,

// System.IO.FileShare.ReadWrite);

lock(oFileInfo)

{

FileStream fs = new FileStream(oFileInfo.FullName, FileMode.Open,
FileAccess.Write,

System.IO.FileShare.Read);

StreamWriter w = new StreamWriter(fs);

w.Write("\r\nLog Entry : ");

w.WriteLine("{0} {1}", DateTime.Now.ToLongTimeString(),

DateTime.Now.ToLongDateString());

w.WriteLine(" :");

w.WriteLine(" :{0}", errorMessage);

w.WriteLine
("----------------------------------------------------------------");

// Update the underlying file.

w.Flush();

// Close

w.Close();

}


}
 
M

Mullin Yu

i tried to make it sleep when throwing the exception of log file is accessed
by another process. is it practical to do so?

my modified code is as follow:

private void LogError2File(string errorMessage, string LogFilePath)

{

FileInfo oFileInfo = new FileInfo(LogFilePath);

DirectoryInfo oDirInfo = new DirectoryInfo(oFileInfo.DirectoryName);


if(!oDirInfo.Exists)

oDirInfo.Create();

if(!oFileInfo.Exists)

oFileInfo.Create();


while(!this.writeFile(errorMessage, LogFilePath))

{

Thread.Sleep(50); // 0.05s

}



}

private bool writeFile(string message, string logPath)

{

try

{

StreamWriter w = File.AppendText(logPath);

w.Write("\r\nLog Entry : ");

w.WriteLine("{0} {1}", DateTime.Now.ToLongTimeString(),

DateTime.Now.ToLongDateString());

w.WriteLine(" :");

w.WriteLine(" :{0}", message);

w.WriteLine
("----------------------------------------------------------------");

// Update the underlying file.

w.Flush();

// Close

w.Close();

return true;

}

catch(Exception ex)

{

return false;

}

}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top