解决关闭 StreamWriter 后使用中的异常文件

发布于 2024-11-05 06:54:11 字数 2140 浏览 0 评论 0原文

我收到错误:

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.

我的程序刷新、关闭并处置日志文件。我的程序稍后尝试打开该文件以附加更多数据。第二次打开会导致上述异常。

在直接访问二进制文件或使用 MS Visual C# Express 2008 在调试模式下运行的执行过程中,Process Explorer 不会显示文件的句柄。

不应显示其他进程使用此文件,因为它是我的应用程序创建的原始文件。

Stack Overflow 中的一些解决方案建议实现 using 语句,但这是不可行的,因为数据写入不会发生在简单或简短的复合语句中。日志记录类使用写入器委托将数据写入文件。

根据 Stack Overflow 中的其他解决方案,在 for 循环中,在打开文件的下一次迭代之前可能不会关闭文件。我等了 10 多秒才再次打开文件,但无济于事(同样的例外)。

以下是代码示例:

    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;

由于我要在截止日期前完成任务,因此我正在寻找此问题的解决方案。我的一些想法是:

  1. 保持文件打开;不要打开和关闭 在测试运行期间。
  2. 显示“等待文件”消息 轮询文件时向用户发送(至 看看什么时候可以再次打开)
  3. 编写非托管 C 或 C++ 处理文件 I/O 的库 (因为非托管 C 和 C++ 不使用 .NET 框架)。
  4. 学习如何辨别 .NET 框架加快并关闭 文件。

我在 Windows 7 64 位架构上使用 MS Visual C# 2008 Express。

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 program 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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

微暖i 2024-11-12 06:54:11
  1. 如果你想把事情做好,你就必须花一些时间。或者
  2. 使用跟踪日志记录 框架。
  3. 我猜您正在使用 Visual Studio Hosting Process 进行调试。尝试禁用它并检查文件锁定问题是否消失。

禁用复选框

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

也可能是您在应用程序关闭期间正在跟踪终结器之一,其中 StreaWriter 已关闭。您可以使用关键终结器来解决这个问题


阿洛伊斯·克劳斯

  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

薄暮涼年 2024-11-12 06:54:11

我希望能为您提供一个快速的解决方案,即将 FileMode.OpenorCreate 替换为 FileMode.Append

正如其他人指出的那样,还有无数其他日志记录选项,但我相信这可能会为您提供一种快速前进的方法,而不是倒退前进。

在我看来,您的代码是一个类的片段,它将流编写器返回到调用上下文。我会让你的类实现 IDisposable 更改你对 Dispose 的关闭(以实现 IDisposable),然后让你的消费者将调用包装到 using(yourLogClass logger = new yourLogClass())... 等以确保关闭被调用每次使用。

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.

GRAY°灰色天空 2024-11-12 06:54:11

调用此类中的方法的代码在调用 open 方法后不会调用 close() 方法。根据您发布的代码,我假设有一个单独的打开方法。如果该方法被调用多次,那么您将得到您所描述的异常。您发布的代码不存在会导致您收到异常的问题。如果你在调用 Close() 之前调用 Flush() ,它将强制写入磁盘,这样当你调用 Close() 时就不会出现延迟。 我通过在一两秒内打开和关闭文件数百次来锤击文件,并且从不这样做有这个问题。

更新:如果您的代码在调试时抛出异常,VS 仍然对该文件有一个打开的句柄。即使您更正了代码,它也会继续抛出该异常。我通常只是关闭并重新启动 VS,以免弄乱我的项目设置并意外地将它们签入源代码管理。

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.

两相知 2024-11-12 06:54:11

我通过保持文件打开来解决这个问题,这样就不需要每次都重新打开它。

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文