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

Doc*_*slo 4 c# io locking file

我不知道如何解决我的问题.我不时会收到错误:"进程无法访问文件'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();
        }
Run Code Online (Sandbox Code Playgroud)

我得到的错误:

************** 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)
Run Code Online (Sandbox Code Playgroud)

Eri*_*ert 9

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

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

  • 好点子.OP,如果您认为可能是这种情况,那么运行[Process Explorer](http://technet.microsoft.com/en-us/sysinternals/bb896653.aspx)并确认是这种情况是值得的. (2认同)

Sam*_*ica 1

我的猜测是你的FileStream(你传递给构造函数的那个StreamReader​​)没有被关闭

StreamReader reader = new StreamReader(new FileStream(filepath, FileMode.Open, FileAccess.Read, FileShare.Read));
Run Code Online (Sandbox Code Playgroud)

将该语句放在 using 语句中,以确保您的所有目的都已绑定

using(StreamReader reader = new StreamReader(new FileStream(filepath, FileMode.Open, FileAccess.Read, FileShare.Read)))
{
    //the using statement will handle the closing for you
}
Run Code Online (Sandbox Code Playgroud)