C# 文件正在被另一个进程使用

标签 c# file io locking

我不确定如何解决我的问题。我不时收到错误: “该进程无法访问文件 'xxxx',因为它正被另一个进程使用”。

这是我的错误发生的方法:

private static void write_history(int index, int time_in_sec, int[] sent_resources)
        {
            string filepath = "Config\\xxx.txt";
            int writing_index = 0;

            if (File.Exists(filepath))
            {
                System.Threading.Thread.Sleep(5000);
                StreamReader reader = new StreamReader(new FileStream(filepath, FileMode.Open, FileAccess.Read, FileShare.Read));
                string temp = reader.ReadToEnd();
                reader.Close();

                for (int i = 0; i < 20; i++)
                {
                    if (temp.IndexOf("<hst_" + i.ToString() + ">") == -1)
                    {
                        writing_index = i;
                        break;
                    }
                }
            }

            System.Threading.Thread.Sleep(5000);
            // write to the file
            StreamWriter writer = new StreamWriter(filepath, true);
            writer.WriteLine("<hst_" + writing_index.ToString() + ">" + DateTime.Now.AddSeconds(time_in_sec).ToString() + "|" + sent_resources[0] + "|" + sent_resources[1] + "|" + sent_resources[2] + "|" + sent_resources[3] + "</hst_" + writing_index.ToString() + ">");
            writer.Close();
        }

我得到的错误:

************** Exception Text **************
System.IO.IOException: The process cannot access the file 'Config\\xxx.txt' because it is being used by another process.
   at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
   at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath)

最佳答案

如果您确定确实正确地打开和关闭了文件,那么最有可能的罪魁祸首就是您的病毒检测器。病毒检测器因观察日志文件已更改而臭名昭著,打开它以搜索病毒,然后当病毒检查器正在读取它时,尝试写入文件失败。

如果是这种情况,那么我会询问病毒检查程序的供应商他们推荐的解决方法是什么。

关于C# 文件正在被另一个进程使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16285342/

相关文章:

c# - 使用 WCF 数据服务时出错

c# - 如何在MVVMCross WPF应用程序中实现关闭按钮?

c# - 如何填充字符串的类列表?

java - 将泛型类型对象写入 java 文件

c# - C# 中的时间延迟

c - 如何用C语言解决这个问题?

媒体文件元数据的 C# 包装器

c++ - 加载一批图像 - 线程分配

tomcat - 当 Tomcat(嵌入式)服务器变慢并最终变得无响应时,最常见的原因是什么

c++ - 我如何重新排列它以便输入 Ctrl-z(文件结束信号)中断循环,同时仍在 C++ 中测试有效输入