2009-11-20 56 views
0

我有在網絡中發送的壓縮文件的問題。所有其他格式的我能夠除了.zip文件發送..幫助:zip文件流

我嘗試了很多我不就沒怎麼做..代碼我寫在客戶端上傳文件,這是微軟建議這裏是link

我能夠創建zip文件,如果我試圖打開它說損壞..文件的大小也不盡相同。

這裏是代碼

public void UploadFile(string localFile, string uploadUrl) 
    { 

     HttpWebRequest req = (HttpWebRequest)WebRequest.Create(uploadUrl); 

     req.Method = "PUT"; 
     req.AllowWriteStreamBuffering = true; 

     // Retrieve request stream and wrap in StreamWriter 
     Stream reqStream = req.GetRequestStream(); 
     StreamWriter wrtr = new StreamWriter(reqStream); 

     // Open the local file 


     Stream Stream = File.Open(localFile, FileMode.Open); 

     // loop through the local file reading each line 
     // and writing to the request stream buffer 

     byte[] buff = new byte[1024]; 
     int bytesRead; 
     while ((bytesRead = Stream.Read(buff, 0,1024)) > 0) 
     { 
      wrtr.Write(buff); 
     } 



     Stream.Close(); 
     wrtr.Close(); 

     try 
     { 
      req.GetResponse(); 
     } 
     catch(Exception ee) 
     { 

     } 

     reqStream.Close(); 

請幫我...

感謝

回答

1

的主要問題是,你正在使用一個StreamWriter,這是一個TextWriter,專爲文本數據,而不是像zip文件這樣的二進制文件。

此外還有Jacob提到的問題,以及您在收到回覆之前沒有關閉請求流的事實 - 儘管這不會產生任何影響,因爲StreamWriter會先關閉它。

下面是固定代碼,更改爲使用using語句(以避免使流打開),更簡單地調用File類,以及更有意義的名稱(IMO)。

using (Stream output = req.GetRequestStream()) 
using (Stream input = File.OpenRead(localFile)) 
{ 
    // loop through the local file reading each line 
    // and writing to the request stream buffer 

    byte[] buffer = new byte[1024]; 
    int bytesRead; 
    while ((bytesRead = input.Read(buffer, 0, 1024)) > 0) 
    { 
     output.Write(buffer, 0, bytesRead); 
    } 
} 

注意,您可以方便地提取while循環到一個輔助方法:

public static void CopyStream(Stream input, Stream output) 
{ 
    // loop through the local file reading each line 
    // and writing to the request stream buffer 

    byte[] buffer = new byte[1024]; 
    int bytesRead; 
    while ((bytesRead = input.Read(buffer, 0, 1024)) > 0) 
    { 
     output.Write(buffer, 0, bytesRead); 
    } 
} 

從其它地方使用,只留下:

using (Stream output = req.GetRequestStream()) 
using (Stream input = File.OpenRead(localFile)) 
{ 
    CopyStream(input, output); 
} 
+0

是......你是對的... 謝謝非常感謝很多人.. – Naruto 2009-11-20 07:19:09