循环执行文件访问检查的最佳方法 [英] Best way to implement a file access check in a loop

查看:72
本文介绍了循环执行文件访问检查的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

这是我的代码:

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

推荐答案

前几天我写了这篇文章.

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

您必须自己声明MaxRetriesIterationThrottleMS,或者也许将它们设为参数.

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

这篇关于循环执行文件访问检查的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆