0

I have this snippet of code below, were I am processing a list of files and moving them to a destination folder.

I already have a specific check in here for a file that is being copied to the network which I want to keep.

Is there anyway I could add another specific check in here that if a file is locked that I can ignore it and move onto the next one and continue on with the processing of the files?

public List<string> ProcessFiles()
{
    string[] fileEntries = Directory.GetFiles(this.SourceLocation);
    List<string> processedFiles = new List<string>();

    foreach (string sourceFile in fileEntries)
    {
        //Verify the destination path exists and attempt move
        if (Directory.Exists(destinationPath))
        {
            try
            {
                //Move the file to destination
                File.Move(sourceFile, destinationFile);
            }
            catch(System.InvalidOperationException io)
            {
                //File is still being copied to the network, wait and try again
                System.Threading.Thread.Sleep(500);
                File.Move(sourceFile, destinationFile);
            }
            processedFiles.Add(fileNameNoPath);
        }

    }
    return processedFiles;
}
H H
  • 263,252
  • 30
  • 330
  • 514
John
  • 85
  • 1
  • 7
  • Instead of checking if it's locked you can simply ignore any errors which appears during copying file (but of course log/display them). Which is a simple `try/catch(Exception)` inside `foreach`. As you already doing, but without second attempt (which may `throw` btw) and sleeping. `processedFiles.Add` should be inside `try` (after `File.Move`) so it will only remember successfully moved files. Current code assumes what second `File.Move` is always successful, which I doubt will be. *Retry* operation is typically organized with Queue and number of attemps. – Sinatr Nov 20 '15 at 09:46
  • Thanks for help Sinatr – John Nov 20 '15 at 14:45
  • Thanks for help Henk – John Nov 20 '15 at 14:46

1 Answers1

1

You can simplify your try/catch block:

try
{
    File.Move(sourceFile, destinationFile);
    processedFiles.Add(fileNameNoPath);
}
catch (System.IO.IOException e)
{
    return;
}
tezzo
  • 10,858
  • 1
  • 25
  • 48