The process cannot access the
file "D:\Log\exceptionLog_2003_01_21.xml" because it is
being used by another process
Below is the code I am using to write to the log file:
//Write element to the existing log file
TextWriter output = File.AppendText(logFilePath);
output.WriteLine(logElem.OuterXml);
output.Close();
output = null;
What is wrong with this approach, and would changing it to
the code below fix it?
//Write element to the existing log file
using (TextWriter output = File.AppendText(logFilePath))
{
output.WriteLine(logElem.OuterXml);
output.Close();
}
Thanks in advance
using ( FileStream fs = File.Open(fileName, FileMode.Append
,FileAccess.Write,FileShare.ReadWrite ) )
{
using ( StreamWriter writer = new StreamWriter(fs) )
{
writer.Write(logElem.OuterXml);
}
}
Note, though, that this allows XML that is not well-formed, as there is no
single document element. This is much faster than trying to insert new data
before the end of the ending tag. When you read your log file, just make
sure to wrap the contents with a document element before loading it into a
DOM (it will not display in IE).
--
Kirk Allen Evans
Author, "XML And ASP.NET", New Riders Publishing
www.xmlandasp.net
http://dotnetweblogs.com/kaevans
"KT" <kttab...@yahoo.com> wrote in message
news:093c01c2cdff$f33470d0$d7f82ecf@TK2MSFTNGXA14...
That won't work either. There's no guaruntee that the output will be
interleaved with other output if two or more threads/processes are trying to
write concurrently.
You should use a Mutex to ensure thread safety.
e.g.
Stream stream;
TextWriter writer;
Mutex mutex = new Mutex(false, "mymutex.blah.blah");
if (!mutex.WaitOne())
{
// report error
return;
}
try
{
stream = new File.Open(.....);
using (stream)
{
writer = new StreamWriter(fs);
writer.Write(.....);
}
}
finally
{
mutex.ReleaseMutex();
}
PS. There's no need to put a using statement around both the stream and the
writer. Disposing the writer disposes the underlying stream.
^Tum
As for the duplicitous using statements, I agree, but think it yields to
maintainability to duplicate. It shouldn't have any side-effects, correct?
--
Kirk Allen Evans
Author, "XML And ASP.NET", New Riders Publishing
www.xmlandasp.net
http://dotnetweblogs.com/kaevans
"Thong Nguyen" <tum[#NOSPAM#]@veri[#NOSPAM#]dicus.com> wrote in message
news:ef2N2OozCHA.2288@TK2MSFTNGP09...
It doesn't have an side-effects. It might be slightly slower -- but not
enough to notice unless the method is a hotspot.
^Tum