2013-02-12 76 views
4

控制器:C#BinaryReader在无法访问已关闭的文件

private readonly Dictionary<string, Stream> streams; 

     public ActionResult Upload(string qqfile, string id) 
     { 
      string filename; 
      try 
      { 
       Stream stream = this.Request.InputStream; 
       if (this.Request.Files.Count > 0) 
       { 
        // IE 
        HttpPostedFileBase postedFile = this.Request.Files[0]; 
        stream = postedFile.InputStream; 
       } 
       else 
       { 
        stream = this.Request.InputStream; 
       } 

       filename = this.packageRepository.AddStream(stream, qqfile); 
      } 
      catch (Exception ex) 
      { 
       return this.Json(new { success = false, message = ex.Message }, "text/html"); 
      } 

      return this.Json(new { success = true, qqfile, filename }, "text/html"); 
     } 

方法添加流:

 public string AddStream(Stream stream, string filename) 
     { 

      if (string.IsNullOrEmpty(filename)) 
      { 
       return null; 
      } 

      string fileExt = Path.GetExtension(filename).ToLower(); 
      string fileName = Guid.NewGuid().ToString(); 
      this.streams.Add(fileName, stream); 
     } 

我想读一个二进制流,像这样:

Stream stream; 
      if (!this.streams.TryGetValue(key, out stream)) 
      { 
       return false; 
      } 

    private const int BufferSize = 2097152; 

          using (var binaryReader = new BinaryReader(stream)) 
          { 
           int offset = 0; 
           binaryReader.BaseStream.Position = 0; 
           byte[] fileBuffer = binaryReader.ReadBytes(BufferSize); // THIS IS THE LINE THAT FAILS 
    .... 

当我在调试模式下查看流,它显示它可以是read = true,seek = true,lenght = 903234等。

,但我不断收到: 无法访问已关闭的文件

,当我在本地运行MVC的网站/调试模式(VS IIS)这工作得很好,不会当“释放”模式(在网站就是工作发布到iis)。

我做错了什么?

+1

请出示其中/ stream'是如何定义'。 – 2013-02-12 12:25:08

+0

添加控制器和添加流方法 – ShaneKm 2013-02-12 12:32:29

回答

7

实测溶液这里:

uploading file exception

解决方案:

增加生产envirenment “requestLengthDiskThreshold”

<system.web> 
<httpRuntime executionTimeout="90" maxRequestLength="20000" useFullyQualifiedRedirectUrl="false" requestLengthDiskThreshold="8192"/> 
</system.web> 
+0

shane!我也遇到这个错误,我会添加这个?在网络配置文件?在生产环境中?谢谢:) – user2705620 2013-10-17 08:56:04

+0

在你的web.config文件子句 – ShaneKm 2013-10-17 12:38:31

+0

谢谢@shane :)已经解决了这个:) – user2705620 2013-10-18 00:54:58

0

看来你依赖于你不控制的对象的生命周期(HttpRequest对象的属性)。如果您希望存储流的数据将是更安全的,立即将数据复制到一个字节数组或类似

你可以改变AddStream到

public string AddStream(Stream stream, string filename) 
    { 

     if (string.IsNullOrEmpty(filename)) 
     { 
      return null; 
     } 

     string fileExt = Path.GetExtension(filename).ToLower(); 
     string fileName = Guid.NewGuid().ToString(); 
     var strLen = Convert.ToInt32(stream.Length); 
     var strArr = new byte[strLen]; 
     stream.Read(strArr, 0, strLen); 
     //you will need to change the type of streams acccordingly 
     this.streams.Add(filename,strArr); 
    } 

那么你可以使用,当你需要的数组流的,让你的对象的生命周期的完全控制的数据的数据被存储在

相关问题