• 欢迎光临~

C# The process cannot access the file 'XXX' because it is being used by another process.

开发技术 开发技术 2022-07-27 次浏览

在读取文件时报进程占用

1.将后台进程杀掉

/// <summary>
/// 杀掉FoxitReader进程
/// </summary>
/// <param name="strProcessesByName"></param>
public static void KillProcess(string processName)
{
    foreach (Process p in Process.GetProcesses())
    {
        if (p.ProcessName.Contains(processName))
        {
            try
            {
                p.Kill();
                p.WaitForExit(); // possibly with a timeout
                Console.WriteLine($"已杀掉{processName}进程!!!");
            }
            catch (Win32Exception e)
            {
                Console.WriteLine(e.Message.ToString());
            }
            catch (InvalidOperationException e)
            {
                Console.WriteLine(e.Message.ToString());
            }
        }
 
    }
}

2.改变读取方式

using (var stream = new FileStream(filePath, FileMode.Open))
{
}

改为下面代码

using (var stream = new FileStream(filePath, FileMode.Open,FileAccess.Read,FileShare.ReadWrite))
{
}
喜欢 (0)