2013-08-06 15 views
0

我在使用filestream將字節附加到文件時遇到問題。我有一個客戶端應用程序,它將文件字節拆分爲n次而不是單次發送,並將其發送到webservice。在Web服務中發生C#FileStream IO異常

我的web服務代碼如下

public bool TransferFile(byte[] bytes, ref string token, ref string path, string extension) 
    { 
     string folderPath = string.Empty; 
     if (System.Configuration.ConfigurationManager.AppSettings["DepositPath"] != null) 
     { 
      folderPath = System.Configuration.ConfigurationManager.AppSettings["DepositPath"].ToString(); 
     } 
     if (string.IsNullOrEmpty(token)) 
     { 
      token = Guid.NewGuid().ToString();    
     } 
     path = Path.Combine(folderPath, token + extension); 

     if (!File.Exists(path)) 
     { 
      using (FileStream fs = File.Create(path)){ 
       fs.Dispose(); 
      } 
     } 
     using (FileStream stream = new FileStream(path, FileMode.Append, FileAccess.Write, FileShare.Write)) 
     { 
      stream.Write(bytes, 0, bytes.Length); 
      stream.Flush(); 
      stream.Close(); 
      stream.Dispose(); 
     } 
     return true; 
    } 

我已經在追加模式下打開文件並追加字節並關閉流。 即使我得到IOException,它說某些其他進程正在使用文件。 我也配置了應用程序池標識。提供了一些想法來解決這個問題。

System.Web.Services.Protocols.SoapException:服務器無法處理請求。 ---> System.IO.IOException:進程無法訪問文件'D:\ Development Projects \ IAM \ FileTransporter \ DepositFolder \ 79ede99d-d76a-4050-959d-17bb87fa6fdb.exe',因爲它正在被另一個進程使用。 (System.IO.FileStream.Init(String path,FileMode mode,FileAccess訪問,Int32權限,布爾useRights,FileShare共享,Int32 bufferSize,FileOptions選項)下的System.IO錯誤 錯誤.WINIOError(Int32 errorCode,String maybeFullPath) ,SECURITY_ATTRIBUTES secAttrs,字符串MSGPATH,布爾bFromProxy) 在System.IO.FileStream..ctor(字符串路徑,的FileMode模式,FileAccess的訪問,文件共享份額) 在FileTransporterService.Service.TransferFile(字節[]字節,字符串&令牌字符串&路徑,字符串擴展名)在D:\ Development Projects \ IAM \ FileTransporter \ FileTransporterService \ Service.asmx.cs中:第36行 ---內部異常堆棧跟蹤結束---

回答

0

如果條件GC.Collect的()將realese該文件

if (!File.Exists(path)) 
{ 
    using (FileStream fs = File.Create(path)){ 
      fs.Dispose(); 
    } 
} 
gc.collect() 
0

我會懷疑有與第一using語句創建該文件時,它不存在問題的資源之後。當您嘗試使用第二條使用語句重新打開文件時,操作系統可能不會刷新和關閉此文件。

確實沒有理由這樣做,您可以使用FileMode.OpenOrCreate選項創建FileStream,它可以完成您嘗試打開文件兩次的相同事情。另外,沒有理由在流上顯式調用Dispose()。使用說明的目的是爲了如何爲您調用Dispose。

試試這個:

public bool TransferFile(byte[] bytes, ref string token, ref string path, string extension) 
    { 
     string folderPath = string.Empty; 
     if (System.Configuration.ConfigurationManager.AppSettings["DepositPath"] != null) 
     { 
      folderPath = System.Configuration.ConfigurationManager.AppSettings["DepositPath"].ToString(); 
     } 
     if (string.IsNullOrEmpty(token)) 
     { 
      token = Guid.NewGuid().ToString(); 
     } 
     path = Path.Combine(folderPath, token + extension); 

     using (var stream = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write, FileShare.Write)) 
     { 
      stream.Write(bytes, 0, bytes.Length); 
      stream.Flush(); 
      stream.Close(); 
     } 
     return true; 
    }