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

本文关键字:检查 最佳 方式 访问 文件 循环 实现 | 更新日期: 2023-09-27 17:58:25

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

这是我的代码:

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

    while (true)
{
    if (SecurityManager.IsGranted(writePermission))
        break;
    Thread.Sleep(1000);
}

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

我前几天写了这篇文章。

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