开发者

what would happen when i try to continue the loop within the catch block

开发者 https://www.devze.com 2023-02-17 06:00 出处:网络
what would happen while searching the file through a string and could i try to continue the loop within the catch block against locked windows file in order to read next file.

what would happen while searching the file through a string and could i try to continue the loop within the catch block against locked windows file in order to read next file.

TextReader rf开发者_如何学JAVAf = null;
try
{
    rff = new StreamReader(fi.FullName);
    String lne1 = rff.ReadToEnd();
    if (lne1.IndexOf(txt) >= 0)
    {
        z = fi.FullName;
        list22.Add(fi.FullName);


As long as the exception is caught by a try-catch nested inside the loop, you should be able to continue the loop no problem.


I'd say you'll have a try-catch around the statement where you are accessing the file within the loop. Then you can continue the loop after catching any exception.


While catching the exception try to catch only the most specific exception that may be thrown, so if you are looking to handle a locking situation you would look to catch the System.IO.IOException which is raised when files are used by other proccesses.


If you have to do some cleanup to do you should add a finally:

foreach (var fileName in fileNames)
{

    var fi = new FileInfo(fileName);
    StreamReader reader;
    try
    {
        reader = new StreamReader(fi.FullName);
        SomeMethodThatThrowsIOException();
    }
    catch (IOException ex)
    {
        continue;
    }
    finally
    {
        if (reader != null)
            reader.Close();
    }
}

or even better (since StreamReader implements IDisposable)

foreach (var fileName in fileNames)
{

    try
    {

        var fi = new FileInfo(fileName);
        using (var reader = new StreamReader(fi.FullName))
        {
            SomeMethodThatThrowsIOException();
        } 
    }
    catch (IOException ex) { }

}
0

精彩评论

暂无评论...
验证码 换一张
取 消