c# - 在 while 循环期间文件正在被另一个进程使用 (C#)

标签 c# .net windows

我目前有一个 while 循环,其中包含一个 if 语句:

if (s.Contains("mp4:production/CATCHUP/"))

虽然当此条件为真时,我尝试使用其他方法(如下所示,例如 RemoveEXELog),但我得到一个访问被拒绝的过程,该进程当前正在使用文件“Command.bat”。

如何在执行其他方法时停止循环文件?

private void CheckLog()
{
    while (true)
    {
        Thread.Sleep(5000);
        if (!System.IO.File.Exists("Command.bat")) continue;
        using (System.IO.StreamReader sr = System.IO.File.OpenText("Command.bat"))
        {
            string s = "";
            while ((s = sr.ReadLine()) != null)
            {
                if (s.Contains("mp4:production/CATCHUP/"))
                {

                    RemoveEXELog(); // Deletes a specific keyword from Command.bat

                    Process p = new Process();
                    p.StartInfo.WorkingDirectory = "dump";
                    p.StartInfo.FileName = "test.exe";
                    p.StartInfo.Arguments = s;
                    p.Start();

                    ClearLog(); // Deletes Command.bat and then creates a new empty Command.bat
                }
            }
        }
    }
}

最佳答案

其他解决方案应该适合您,但是,您也可以像这样打开文件:

using (var sr = new FileStream("Command.bat", FileMode.Open, 
                               FileAccess.Read, FileShare.ReadWrite))
{
    ...
}

这将以只读模式打开文件。

然后在您的 RemoveEXELog() 方法中,您可以像这样打开它:

using (var sr = new FileStream("Command.bat", FileMode.Open, 
                               FileAccess.ReadWrite, FileShare.ReadWrite))
{
    ...
}

这种方法应该允许您从两个位置打开文件,而不会出现文件已在使用中的 I/O 异常。

关于c# - 在 while 循环期间文件正在被另一个进程使用 (C#),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6719773/

相关文章:

c# - Type.GetInterfaces() 仅用于声明的接口(interface)

c# - C# 中的运算符重载

c# - 在 Windows 7/.Net 4.0 上将多页 Tiff 拆分为单个 Tiff

C#, 需要获取文件创建时间

c# - 一种抽象子流程成功/失败的方法

python - Firefox 附加组件 SDK 错误

c# - 如何使用 roslyn 获得一种方法体的 il?

字符串值中的 C# LINQ 日期时间

c++ - 使用 CryptoAPI Next Generation (CNG) 加密数据的直接示例

.net - 所有不同的X509KeyStorageFlags的基本原理是什么?