开发者

Resolving exception file in use after closing StreamWriter

I am getting the error:

The process cannot access the file 
'C:\AMR_VOYANT_TESTING\PWM_TESTER\UUT_LOGS\TEST_LOG_PWM_10245_UUT_SN_10.TXT'
because it is being used by another process.

My program flushes, closes, and disposes the log file. My pr开发者_Python百科ogram later attempts to open the file to append more data. This 2nd opening causes the above exception.

Process Explorer does not show the handle of the file, during execution either directly accessing the binary file or running in debug mode with MS Visual C# Express 2008.

No other processes should be using this file since it is an original file created by my application.

Some solutions in Stack Overflow suggest implementing a using statement, but this is not feasible because the writing of data does not occur in a simple or short compound statement. A writer delegate is used by a logging class to write data to the file.

According to other solutions in Stack Overflow, in a for loop, a file may not be closed before the next iteration where the file is opened. I've waited over 10 seconds before opening the file again, to no avail (same exception).

Here is a sample of the code:

    public void
    close()
    {
        get_log_file().WriteLine("");
        get_log_file().Flush();
        get_log_file().Close();
        get_log_file().Dispose();
        m_log_file = null;
        return;
    }


    private StreamWriter
    get_log_file()
    {
        if (m_log_file == null)
        {
            bool successful = false;
            int retries_remaining = 5;
//                do
//                {
//                    try
//                    {            
//                        m_log_file = new StreamWriter(m_filename, true);
                m_log_file = new StreamWriter(new FileStream(m_filename, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None));
//                    }
//                    catch (IOException)
//                    {

//                        --retries_remaining;
//                        System.Threading.Thread.Sleep(250); // Units are in milliseconds;
//                    }
//                } while (!successful && (retries_remaining >= 0));
            }
            return m_log_file;
        }
        private System.IO.StreamWriter m_log_file = null;
        private string m_filename;

Since I have a deadline to meet, I'm looking for resolutions to this issue. Some of my ideas are:

  1. Keep file open; don't open and close during test runs.
  2. Display a "waiting for file" message to user while polling the file (to see when it can be opened again)
  3. Writing an unmanaged C or C++ library to handle the file I/O (since unmanaged C and C++ don't use the .NET framework).
  4. Learning how to tell the .NET framework to hurry up and close the file.

I'm using MS Visual C# 2008 Express on Windows 7, 64-bit architecture.


  1. If you want to do it right you have to spend some time. Or
  2. Use a tracing or logging framework.
  3. I guess you are debugging with the Visual Studio Hosting Process. Try to disable it and check if the file locking issue goes away.

Disable the checkbox of

Project - Properties - Debug - x Enable Visual Studio hosting process

It could also be that you are tracing in one of your finalizers during application shutdown where the StreaWriter was already closed. You can get around this by using a Critical Finalizer

Yours, Alois Kraus


What I hope will offer you a quick solution is to replace FileMode.OpenorCreate with FileMode.Append;

As others are pointing out there are a myriad of other logging options, but I believe this may offer you a quick way forward from where you stand rather than going backwards to get forwards.

It looks to me as your code is a fragment of a class that returns the streamwriter to a calling context. I would make your class implement IDisposable change your close to Dispose (to implment IDisposable) and then make your consumer wrap the call into a using(yourLogClass logger = new yourLogClass())... etc. to insure that the close is being called with each use.


Code that is calling methods in this class are not calling your close() method after calling the open method. Based on the code you have posted I assume there is a separate open method. If that method is called more than once then you will get the exception you are describing. The code you have posted has no problems that would cause the exception you are getting. If you call Flush() before calling Close() it will force a write to disk so that there is no delay when you call Close() I have hammered files by opening and closing them hundreds of times within a second or two, and never had this problem.

Update: if your code threw an exception while you were debugging it, VS still has an open handle on that file. It will continue to throw that exception even if you have corrected your code. I usually just close and restart VS so as not to mess with my project settings and accidentally check them into source control.


I resolved this issue by keeping the file open which removed the need to re-open it each time.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜