简体   繁体   中英

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. 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:

System.IO.IOException: 'The process cannot access the file 'C:\\Windows\\Fonts\\app.EXE' because it is being used by another process.'

and it only tries to copy it.

Putting aside the fact that it's weird to be moving .exe files into your Font folder...

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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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