Releasing file locks

D

David Veeneman

I have a maddening problem that I hope someone can help with. I have some
code that writes temporary documents to the data folder of my web site. On
one document, I keep getting an error "The process cannot access the file
'myFile.txt' because it is being used by another process."

Simple failure to wrap a stream writer in a try-catch-finally block, right?
Not so--here's the code in question:

***********************************************************************************

string filePath = String.Format(@"{0}\Documents\myFile.txt", dataPath);
string msg = String.Empty;
try
{
// Create StreamWriter
streamWriter = new StreamWriter(filePath, false);

// Write file
streamWriter.WriteLine(SomeText);
}
catch (Exception e)
{
// Log error message
msg = e.Message;
}
finally
{
// Close and dispose
if (streamWriter != null)
{
streamWriter.Close();
streamWriter.Dispose();

// Log if the file stream was closed
msg = "File stream closed and disposed";
}
}

// Log result
ActivityLog.WriteEntry(msg, dataPath);

*********************************************************************

Here's where it gets really strange: We uncovered the problem in testing. We
can replicate it by forcing an exception in another part of the code for
this page. In other words, the original error is not related to the
temporary file in any way, and we have verified that the Close() method for
this file stream is being called long before the original exception is ever
raised. But the next time the page is loaded, we get the "cannot access"
error.

In other words, even though the file stream is properly closed when the file
is created, on the next page load, it is locked, causing a "cannot access"
exception.

Has anyone come across anything like this? I am totally baffled. Any
suggestions as to how to proceed would be appreciated.

David Veeneman
Foresight Systems
 
D

David Veeneman

The short answer: Look for locks in other parts of the program, which is
where I found my solution.
 

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

Members online

Forum statistics

Threads
473,992
Messages
2,570,220
Members
46,807
Latest member
ryef

Latest Threads

Top