【问题标题】:Getting "File already in Use by other process" when using File.Move, why/how can I fix this?使用 File.Move 时出现“文件已被其他进程使用”,为什么/如何解决这个问题?
【发布时间】:2018-07-18 16:35:17
【问题描述】:

我想用这种方法移动几个名称保存在ObservableCollection<String> _collection 中的文件:

string firstFolderThatContainsEveryFile = "...\Folder\Files";
string secondFolderArchiv = "...\Folder\Files\Archiv";
foreach (var item in _collection)
{
     string firstFolder = System.IO.Path.Combine(firstFolderThatContainsEveryFile, item);
     string secondFolder = System.IO.Path.Combine(secondFolderArchiv, item);
     File.Move(firstFolder, secondFolder);
}

这在第一次工作,但如果我将新文件加载到 firstFolderThatContainsEveryFile 并尝试使用我的移动方法,我会得到一个异常:

文件已被其他进程使用

步骤如下: 我打开程序->使用移动方法->成功->关闭程序->用新文件填充文件夹->打开程序->使用移动方法->异常!

如何在使用 move 方法之前获取进程名称或进程 ID 以关闭进程,或者有更好的方法来解决这个问题?

【问题讨论】:

  • 第二次添加文件之前,您的收藏是否为空?如果不是,您的代码将尝试再次移动相同的文件,这肯定会导致这样的错误。
  • @PetervanderHeijden jes,我的收藏是空的。我打开程序->使用移动方法->成功->关闭程序->用新文件填充文件夹->打开程序->使用移动方法->异常!
  • @Liam omg jes 你是对的,我很抱歉我编辑我的问题
  • 您的第一个停靠港是identifying what is locking the file。如果您关闭程序不应该是您,我在您的代码中也看不到任何可以执行此操作的内容。我想是病毒软件之类的

标签: c# file move


【解决方案1】:

要弄清楚哪个进程正在使用您的文件,使用this提出的解决方案,您可以使用Microsoft的工具Handle和这段代码C#来调用该工具。

        public void ViewProcess(string filePath)
        {
            Process tool = new Process();
            tool.StartInfo.FileName = "handle.exe";
            tool.StartInfo.Arguments = filePath + " /accepteula";
            tool.StartInfo.UseShellExecute = false;
            tool.StartInfo.RedirectStandardOutput = true;
            tool.Start();
            tool.WaitForExit();
            string outputTool = tool.StandardOutput.ReadToEnd();

            string matchPattern = @"(?<=\s+pid:\s+)\b(\d+)\b(?=\s+)";
            foreach (Match match in Regex.Matches(outputTool, matchPattern))
            {
                try{                  
                   Console.WriteLine(match.Value); // this is the process ID using the file
                }
                catch(Exception ex)
                {
                }
            }
        }

如果文件被其他程序使用,你应该弄清楚他们为什么使用它,如果被你的程序使用,那么重新检查你的代码以了解原因。

【讨论】:

  • 他在foreach循环中,所以你只是不想终止他的程序进程?这是不安全的做法,也是不好的做法。
  • @BarrJ 那为什么我告诉他使用代码来调试以查看哪个进程锁定了文件并弄清楚。为什么你确定他的程序正在锁定文件?
  • 因为他在使用文件时没有检查文件是否被锁定。通过代码手动终止进程绝不是一种好习惯,您应该尽可能避免它。
  • 这看起来很危险。最好找出为什么文件被锁定。
  • @BarrJ 不完全同意,但我仍然更新了答案
猜你喜欢
  • 1970-01-01
  • 2021-02-10
  • 2012-11-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多