Process cannot access the file because it is being accessed by another process while writing to a log file
Though this is a very known issue to you all may be, I am getting this exception after all implementing locks and the other requried. But still i get the exception sometimes, but not able to figure out what's happening.
What I am doing is, in my application i m writing some log messages to a text file this way.
WriteToFile(DateTime.Now + "Method1(): Entered", LOG_FILE_NAME);
where the definition of WriteToFile goes this way:
public void WriteToFile(string message,string fileName)
{
try
{
lock (filelock)
{
using (FileStream fs = new FileStream(fileName, FileMode.Append, FileAccess.Write, FileShare.ReadWrite))
{
开发者_如何学C // Create the writer for data.
using (BinaryWriter w = new BinaryWriter(fs))
{
// Write data to Test.data.
w.Write(System.Environment.NewLine);
w.Write(message);
w.Write(System.Environment.NewLine);
}
}
}
}
catch (Exception ex)
{
throw ex;
}
finally
{
}
}
Whenever this exception comes, it throws the exception to the caller, in which i have again written to the file.like this:
public void Method1()
{
try
{
WriteToFile(DateTime.Now + "Method1(): Entered", LOG_FILE_NAME);
}
catch(Exception ex)
{
WriteToFile(DateTime.Now + "Exception in Method1():"+ex.Message, LOG_FILE_NAME);
}
}
But now in Method1() this exception caught was able to written to the file.
So, I seek anyone's help here. Is any other better way of doing logging here?
Thanks & Regads
Padma
If this is your "real world" Problem (logging), you should just use a well tested, working and scalable solution for loging -> microsoft enterprise lib or log4net.
Otherwise please add more/all details on what you try ro achive.
MSDN says that "The My feature gives you better productivity and performance in file I/O operations than Lock and Unlock".
This means you could use my.Computer.FileSystem.WriteAllText() instead. Personally I would create a streamwriter object:
public void WriteToFile(string message, string fileName)
{
System.IO.StreamWriter fstream;
fstream = new System.IO.StreamWriter(fileName,true);
// stream writer adds newline to the end for you
fstream.WriteLine(message);
// flush to send all buffered data to the file
fstream.Flush();
// close the file, free resources
fstream.Close();
}
Also I believe you need to Unlock the file after writing to it, otherwise it might stay locked. Thirdly is there an specific reason you are locking the log file? Like are you writing to it from more than one process at the same time? If not, then I don't see why you need to lock it in the first place.
Is something like this you are looking for? :)
public void WriteToFile(string message,string fileName)
{
try
{
StreamWriter w = File.AppendText(filename)
w.WriteLine(message);
w.Close();
}
catch (Exception ex)
{
throw ex;
}
}
精彩评论