在循环中实现文件访问检查的最佳方法

时间:2011-06-06 13:28:56

标签: c# permissions

我正试图找到一种更好的方法来检查循环中的文件访问。

这是我的代码:

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);
    }
}

这是我到目前为止所尝试的内容,但它无法正常工作:

  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 个答案:

答案 0 :(得分:0)

我前几天写了这篇文章。

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;
        }
    }
}

您必须自己声明MaxRetriesIterationThrottleMS,或者将它们作为参数。

编辑我举了一个例子。正如我承认的那样,除非重新使用,否则这将超过工程量

//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*/}