User6996
User6996

Reputation: 3003

Thread try catch continue if access to file was denied

Looping through a folder using system thread, how to ignore and continue if access to file was denied.

// Start thread.  
System.Threading.ThreadStart start = delegate { scanner(@"C:\", "*.html;*.txt"); };
System.Threading.Thread thread = new System.Threading.Thread(start);
thread.Start();


private static string scanstatus = string.Empty;
private static void scanner(string folder, string patterns) 
{
    try
    {  
        // Get the patterns.
        string[] pattern_array = patterns.Split(';');

        // Search.
        foreach (string pattern in pattern_array)
        {
            foreach (string path in System.IO.Directory.GetFiles(folder, pattern, System.IO.SearchOption.AllDirectories))
            {
                // trim path
                scanstatus = (path.Length > 60) ? "../" + path.Substring(path.Length - 59, 59) : path;

                System.Threading.Thread.Sleep(5000);
            }
        }

    }
    catch (System.Exception excpt)
    {
        Console.WriteLine(excpt.Message);
    }
    finally
    {
        Console.WriteLine("*************DONE*************");
    }

}

Upvotes: 2

Views: 2345

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1499860

As Daniel mentioned in the comment, basically when you want to keep going with the next iteration, you need to move the try/catch to inside the loop. Currently your catch is outside the outer loop, so if an exception is thrown, execution can't continue. There's no concept of "continue from where you'd got to" within C#.

I'd strongly suggest that you also limit what you catch. For example:

foreach (string pattern in patternArray)
{
    try
    {
        foreach (string path in Directory.GetFiles(...))
        {
            // ...
        }
    }
    catch (IOException e)
    {
        // Log it or whatever
    }
    // Any other exceptions you want to catch?
}

Notes:

  • Catching Exception is almost always a bad idea, except as a final backstop at the top level of your request (or whatever) handling
  • Underscores in variable names aren't conventional in .NET; typically you'd use camelCase for variables (and PascalCase for methods, classes etc)
  • With using directives you can avoid putting the fully-qualified type names in your code, which would make it much easier to read
  • This method will end up being quite long - I'd suggest extracting the inner loop; possibly including the try/catch, or possibly not.

Upvotes: 3

Related Questions