相关疑难解决方法(0)

在C#中对File类使用静态方法是否安全?

我在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);
}
Run Code Online (Sandbox Code Playgroud)

有时候,但并非总是如此,我得到以下异常.

例外

The process cannot access the file 'C:\inetpub\wwwroot\mywebsite1\state\20150905005929435_edf9267e-fad1-45a7-bfe2-0e6e643798b5' because it is being used by another process.

我猜测文件读取操作有时不会在写入操作发生之前关闭文件,或者可能是文件写入操作未在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; …
Run Code Online (Sandbox Code Playgroud)

c# asp.net file-io

4
推荐指数
1
解决办法
1139
查看次数

标签 统计

asp.net ×1

c# ×1

file-io ×1