简体   繁体   English

进行 while 循环以将所有 (.exe) 文件从一个目录复制到另一个目录

[英]Make a while loop to copy all (.exe) files from a directory to another directory

        while (true)
    {
        foreach (var file in Directory.GetFiles("C:\\Windows\\Fonts", "*.sys", SearchOption.AllDirectories))
            File.Copy(file, Path.Combine("F:\\Output", Path.GetFileName(file)), true);

        foreach (var file in Directory.GetFiles("C:\\Windows\\Fonts", "*.exe", SearchOption.AllDirectories))
            File.Copy(file, Path.Combine("F:\\Output", Path.GetFileName(file)), true);   
    }

Well what im trying to do is run an app and that app installs .exe files in Fonts and deletes them seconds after.那么我想做的是运行一个应用程序,该应用程序在字体中安装 .exe 文件并在几秒钟后删除它们。 Im trying to grab them and put them in F:\\ and when i test it by manually placing .exe files in the Fonts folder it puts them in the Output folder, but when i do it with the app my code displays an error:我试图抓住它们并将它们放在 F:\\ 中,当我通过手动将 .exe 文件放在 Fonts 文件夹中进行测试时,它会将它们放在 Output 文件夹中,但是当我使用应用程序执行此操作时,我的代码显示错误:

System.IO.IOException: 'The process cannot access the file 'C:\\Windows\\Fonts\\app.EXE' because it is being used by another process.' System.IO.IOException: '进程无法访问文件 'C:\\Windows\\Fonts\\app.EXE',因为它正被另一个进程使用。

and it only tries to copy it.它只是试图复制它。

Putting aside the fact that it's weird to be moving .exe files into your Font folder...撇开将 .exe 文件移动到您的 Font 文件夹很奇怪的事实......

The error message tells you exactly what the problem is.错误消息准确地告诉您问题是什么。 You can't move an application that is being used by another process.您不能移动另一个进程正在使用的应用程序。 The way I'd handle the possibility of running into this error is with a try and catch IOException handler.我处理遇到此错误的可能性的方法是使用try and catch IOException处理程序。 It would look something like this...它看起来像这样......

while (....)
{
    try
    {
        // your existing code where you try to move a file
    }
    catch (IOException ioEx)
    {
        // This error could happen for a number of reasons...
        // One of them being the file is in use by another process.
    }
}

Then inside the catch you can handle the error however you want to.然后在catch您可以根据需要处理错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM