2013-02-12 77 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); 
    } 

那麼你可以使用,當你需要的數組流的,讓你的對象的生命週期的完全控制的數據的數據被存儲在

相關問題