2017-06-15 33 views
1

我有一個簡單的FTP上傳(大多不是我自己的代碼,仍在學習) 它工作得很好,但它正在破壞EXE文件,從我的閱讀周圍,這是因爲它不是一個二進制閱讀器。但令人困惑的是,我正在告訴它使用二進制。FTP FtpWebRequest uploader腐敗EXE文件

這是我的代碼:

private void UploadFileToFTP(string source) 
{ 
    String sourcefilepath = textBox5.Text; 
    String ftpurl = textBox3.Text; // e.g. ftp://serverip/foldername/foldername 
    String ftpusername = textBox1.Text; // e.g. username 
    String ftppassword = textBox2.Text; // e.g. password 

    try 
    { 
     string filename = Path.GetFileName(source); 
     string ftpfullpath = ftpurl + "/" + new FileInfo(filename).Name; 
     FtpWebRequest ftp = (FtpWebRequest)FtpWebRequest.Create(ftpfullpath); 
     ftp.Credentials = new NetworkCredential(ftpusername, ftppassword); 

     ftp.KeepAlive = true; 
     ftp.UseBinary = true; 
     ftp.Method = WebRequestMethods.Ftp.UploadFile; 

     FileStream fs = File.OpenRead(source); 
     byte[] buffer = new byte[fs.Length]; 
     fs.Read(buffer, 0, buffer.Length); 
     fs.Close(); 

     Stream ftpstream = ftp.GetRequestStream(); 
     ftpstream.Write(buffer, 0, buffer.Length); 
     ftpstream.Close(); 
    } 
    catch (Exception ex) 
    { 
     throw ex; 
    } 
} 
+0

怎麼辦你的意思是它工作正常,但腐敗exe文件?它是如何正常工作,如果它是破壞文件? –

+0

因爲上傳的實際功能適用於大多數文件類型。除了.exes –

+0

然後聽起來像是一個編碼問題。也許OpenRead()對編碼做一些簡單的事情。試試我的例子。我只用EXE測試過,它工作正常。 – Cory

回答

0

不知道你有什麼問題。

此代碼工作對我蠻好:

String sourcefilepath = ""; 
String ftpurl = ""; // e.g. ftp://serverip/foldername/foldername 
String ftpusername = ""; // e.g. username 
String ftppassword = ""; // e.g. password 
var filePath = ""; 
try 
{ 
    string filename = Path.GetFileName(sourcefilepath); 
    string ftpfullpath = ftpurl + "/" + new FileInfo(filename).Name; 
    FtpWebRequest ftp = (FtpWebRequest)FtpWebRequest.Create(ftpfullpath); 
    ftp.Credentials = new NetworkCredential(ftpusername, ftppassword); 

    ftp.KeepAlive = true; 
    ftp.UseBinary = true; 
    ftp.Method = WebRequestMethods.Ftp.UploadFile; 

    byte[] buffer = File.ReadAllBytes(sourcefilepath); 

    ftp.ContentLength = buffer.Length; 

    Stream ftpstream = ftp.GetRequestStream(); 
    ftpstream.Write(buffer, 0, buffer.Length); 
    ftpstream.Close(); 
} 
catch (Exception ex) 
{ 
    throw ex; 
} 
+0

我用過這個,但它仍然有效。感謝一羣兄弟: byte [] buffer = new byte [fs.Length]; fs.Read(buffer,0,buffer.Length); ftp.ContentLength = fs.Length; fs.Close(); –

+0

尷尬..:| 。我不知道。感謝您的鏈接。 – Cory

2

Stream.Read並不能保證你念你所要求的所有字節。

具體FileStream.Read documentation說:

計數:要讀取的最大字節數。
返回值:讀入緩衝區的總字節數。如果該字節數當前不可用,則該可能比請求的字節數少,或者如果到達流的末尾則爲零。


要讀取整個文件到內存,使用File.ReadAllBytes

byte[] buffer = File.ReadAllBytes(source); 

雖然你應該實際使用Stream.CopyTo,完全避免存儲大文件到內存:

fs.CopyTo(ftp.GetRequestStream());