How to handling the file concurrency issue?

  • Thread starter Thread starter Mullin Yu
  • Start date Start date
M

Mullin Yu

I create a component to write the error log as follow, but it seems
sometimes locked by other processes, and pop up the I/O exception.

How can we handling the concurrency issue at file level? Retry accessing the
file if catch error => like waiting and polling.

Thanks!

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);

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();

}
 
Mullin,

Instead of calling AppendText, open the FileStream yourself, allowing it
to be shared for read-only access, but you maintain the write access.

Hope this helps.
 
do i need to implement any multiple-producer-consumer pattern at this case?

more than one process/application will write to the error log file.

what's the implementation of commercial software then? like iis log, tomcat
log?

thanks!

regards,
mullin

Nicholas Paldino said:
Mullin,

Instead of calling AppendText, open the FileStream yourself, allowing it
to be shared for read-only access, but you maintain the write access.

Hope this helps.


--
- Nicholas Paldino [.NET/C# MVP]
- (e-mail address removed)

Mullin Yu said:
I create a component to write the error log as follow, but it seems
sometimes locked by other processes, and pop up the I/O exception.

How can we handling the concurrency issue at file level? Retry accessing the
file if catch error => like waiting and polling.

Thanks!

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);

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();

}
 
Back
Top