c# - 在 C# 中的 File 类上使用静态方法是否安全?

标签 c# asp.net file-io

我在 ASP.Net 应用程序的代码隐藏中有以下代码,其中正在读取文件,然后写入文件。

代码

var state= File.ReadAllText(Server.MapPath(string.Format("~/state/{0}", fileName)));
if(state.indexOf("1") == 0) 
{
  File.WriteAllText(Server.MapPath(string.Format("~/state/{0}", fileName)), newState);
}

有时,但并非总是如此,我会遇到以下异常。

异常

进程无法访问文件“C:\inetpub\wwwroot\mywebsite1\state\20150905005929435_edf9267e-fad1-45a7-bfe2-0e6e643798b5”,因为它正被另一个进程使用。

我猜测文件读取操作有时不会在写入操作发生之前关闭文件,或者文件写入操作可能不会在来自 Web 应用程序的下一个请求到来之前关闭文件。但是,我找不到确切的原因。

问题:如何避免此错误的发生?使用 File 类而不是使用 FileStream 对象的传统方法(我总是显式处理 FileStream 对象)是否不安全?

更新 1

我尝试了一种重试循环方法,但即便如此似乎也没有解决问题,因为如果 ASP.Net 页面被一次又一次地快速提交多次,我能够重现相同的错误。因此,我又开始为我的案例寻找万无一失的解决方案。

  string state = null;
  int i = 0;
  while (i < 20) {
    try {

        state = File.ReadAllText(Server.MapPath(string.Format("~/state/{0}", fileName)));

    } catch (Exception ex2) {
        //log exception
        Elmah.ErrorSignal.FromCurrentContext().Raise(ex2);
        //if even retry doesn't work then throw an exception
        if (i == 19) {
            throw;
        }
        //sleep for a few milliseconds
        System.Threading.Thread.Sleep(10);
    }
    i++;
  }

  i = 0;
  while (i < 20) {
    try {


        File.WriteAllText(Server.MapPath(string.Format("~/state/{0}", fileName)), newState);

    } catch (Exception ex2) {
        //log exception
        Elmah.ErrorSignal.FromCurrentContext().Raise(ex2);
        //if even retry doesn't work then throw an exception
        if (i == 19) {
            throw;
        }
        //sleep for a few milliseconds
        System.Threading.Thread.Sleep(10);
    }
    i++;
  }

更新 2

唯一可行的万无一失的解决方案是使用 文件排序 方法,正如 usr 所建议的那样。这涉及写入不同的文件,而不是写入刚刚读取的同一文件。正在写入的文件名是刚刚读取的文件名加上一个序列号。

  string fileName = hiddenField1.Value;
  string state = null;
  int i = 0;
  while (i < 20) {
    try {

        state = File.ReadAllText(Server.MapPath(string.Format("~/state/{0}", fileName)));

    } catch (Exception ex2) {
        //log exception
        Elmah.ErrorSignal.FromCurrentContext().Raise(ex2);
        //if even retry doesn't work then throw an exception
        if (i == 19) {
            throw;
        }
        //sleep for a few milliseconds
        System.Threading.Thread.Sleep(10);
    }
    i++;
  }

  i = 0;
  while (i < 20) {
    try {
        //***************FILE SEQUENCING**************************
        //Change the file to which state is written, so no concurrency errors happen 
        //between reading from and writing to same file. This is a fool-proof solution.
        //Since max value of integer is more than 2 billion i.e. 2,147,483,647
        //so we can be sure that our sequence will never run out of limits because an ASP.Net page
        //is not going to postback 2 billion times
        if (fileName.LastIndexOf("-seq_") >= 0) {
            fileName = fileName.Substring(0, fileName.LastIndexOf("-seq_") + 4 + 1) + (int.Parse(fileName.Substring(fileName.LastIndexOf("-seq_") + 4 + 1)) + 1);
        } else {
            fileName = fileName + "-seq_1";
        }
        //change the file name so in next read operation the new file is read
        hiddenField1.Value = fileName;
        File.WriteAllText(Server.MapPath(string.Format("~/state/{0}", fileName)), newState);

    } catch (Exception ex2) {
        //log exception
        Elmah.ErrorSignal.FromCurrentContext().Raise(ex2);
        //if even retry doesn't work then throw an exception
        if (i == 19) {
            throw;
        }
        //sleep for a few milliseconds
        System.Threading.Thread.Sleep(10);
    }
    i++;
  }

上述方法的唯一缺点是,当最终用户回发到同一个 ASP.Net 页面时,会创建许多文件。因此,最好有一个删除陈旧文件的后台作业,这样可以最大程度地减少文件数量。

带顺序的文件名

File Sequencing Naming

更新 3

另一个万无一失的解决方案是交替读取和写入文件名。这样我们最终不会创建很多文件,并且在最终用户多次回发到同一页面时只使用 2 个文件。代码与 UPDATE 2 下的代码相同,只是 FILE SEQUENCING 注释后的代码应替换为下面的代码。

if (fileName.LastIndexOf("-seq_1") >= 0) {
            fileName = fileName.Substring(0, fileName.LastIndexOf("-seq_1"));
        } else {
            fileName = fileName + "-seq_1";
        }

采用交替方法的文件名 File Alternating Approach

最佳答案

I am guessing that the file read operation sometimes is not closing the file before the write operation happens, Or may be the file write operation is not closing the file before the next request from web application comes.

正确。文件系统不支持原子更新。 (尤其是在 Windows 上;很多怪癖。)

使用 FileStream 没有帮助。您只需重写与 File 类相同的代码。 File 里面没有魔法。为了您的方便,它只是使用 FileStream 包装。

尝试保持文件不可变。当你想写一个新内容时写一个新文件。将序列号附加到文件名(例如 ToString("D9"))。读取时选择序列号最高的文件。

或者,只需添加一个具有小延迟的重试循环。

或者,使用更好的数据存储,例如数据库。文件系统真的很讨厌。这是一个很容易用 SQL Server 解决的问题。

关于c# - 在 C# 中的 File 类上使用静态方法是否安全?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32413634/

相关文章:

c - 这个程序中的 fread 有什么问题?

C - 文件 I/O,不是从文件中读取

php - 如何使用 PHP 将文件从一个目录复制到另一个目录?

c# - 7-Zip 7za 命令行找不到指定的文件

c# - VSTS 中的文件路径

c# - Visual C# Directory.GetDirectories 问题 - "The specified server cannot perform the requested operation"

c# - 在没有完整回发的情况下获取查询字符串值

javascript - asp.net 将 javascript ajax 发送到用户控件

c# - 如何在光标位置裁剪图像的一部分?

c# - 创建一个 asp :Button programmatically?