Best way to implement a file access check in a loo

2019-09-14 05:09发布

问题:

I'm trying to find a better way to check for file access in a loop.

Here's my code:

while (true)
{
    try
    {
        using (FileStream Fs = new FileStream(fileName, FileMode.Open, FileAccess.Write))
        using (StreamReader stream = new StreamReader(Fs))
        {
            break;
        }
}
catch (FileNotFoundException)
{
    break;

}
catch (ArgumentException)
{
    break;
}
catch (IOException)
{
    Thread.Sleep(1000);
    }
}

Here's what I've tried so far, but it does not work has exprected:

  FileIOPermission writePermission = new FileIOPermission(FileIOPermissionAccess.Write, fileName);

while (true)
{
    try
    {
        writePermission.Demand();
        break;
    }
    catch (SecurityException e)
    {
        Thread.Sleep(1000);
    }
}

AND

    while (true)
{
    if (SecurityManager.IsGranted(writePermission))
        break;

    Thread.Sleep(1000);
}

回答1:

I wrote this the other day.

public static void Retry(Action fileAction, int iteration)
{
    try
    {
        fileAction.Invoke();
    }
    catch (IOException)
    {
        if (interation < MaxRetries)
        {
            System.Threading.Thread.Sleep(IterationThrottleMS);
            Retry(fileAction, ++iteration);
        }
        else
        {
            throw;
        }
    }
}

You would have to declare MaxRetries and IterationThrottleMS yourself, or perhaps make them parameters.

EDIT I include an example. As I admit, this would be over engineering unless it were resused

//A little prep

const int IterationThrottleMS = 1000;
const int MaxRetries = 5;

public static void Retry(Action fileAction)
{
    Retry(fileAction, 1)
}

...
// Your first example

try
{
    Retry(() => {
        using (FileStream Fs = new FileStream(
                fileName, 
                FileMode.Open, 
                FileAccess.Write)
            StreamReader stream = new StreamReader(Fs);
    });
}
catch (FileNotFoundException) {/*Somthing Sensible*/} 
catch (ArgumentException) {/*Somthing Sensible*/}
catch (IOException) {/*Somthing Sensible*/}

...
// Your second example

try
{
    Retry(() => writePermission.Demand());
}
catch (FileNotFoundException) {/*Somthing Sensible*/} 
catch (ArgumentException) {/*Somthing Sensible*/}
catch (IOException) {/*Somthing Sensible*/}