2013-10-31 14 views
0

所以我試圖上傳一個文件到我的FTP服務器。每件事似乎都像預期的那樣工作,但是當我從ftp打開文件時,我收到一個I/O錯誤。本地文件工作得很好。上傳後的一些文件如何損壞。我發現了一個類似的問題here上傳到FTP後打開pdf的I/O錯誤

在這裏我讀到,你必須改變傳輸模式爲二進制。我試圖設置ftpRequest.UseBinary = true;但我仍然遇到I/O錯誤。我需要在某個地方更改傳輸模式嗎?

這是我的FTP上傳代碼:

public string upload(string remoteFile, string localFile) 
{ 
    ftpRequest = (FtpWebRequest)FtpWebRequest.Create(host + "/" + remoteFile); 
    ftpRequest.UseBinary = true; 
    ftpRequest.Credentials = new NetworkCredential(user, pass); 
    ftpRequest.Method = WebRequestMethods.Ftp.UploadFile; 

    // Copy the contents of the file to the request stream. 
    StreamReader sourceStream = new StreamReader(localFile); 
    byte[] fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd()); 

    sourceStream.Close(); 
    ftpRequest.ContentLength = fileContents.Length; 
    Stream requestStream = ftpRequest.GetRequestStream(); 

    requestStream.Write(fileContents, 0, fileContents.Length); 
    requestStream.Close(); 

    FtpWebResponse response = (FtpWebResponse)ftpRequest.GetResponse(); 
    response.Close(); 
    return string.Format("Upload File Complete, status {0}", response.StatusDescription); 
} 

使用的WebClient我得到的錯誤:

The remote server returned an error: (553) File name not allowed.

這裏是我的代碼:

private void uploadToPDF(int fileName, string localFilePath, string ftpPath, string baseAddress) 
{ 
    WebClient webclient = new WebClient(); 
    webclient.BaseAddress = baseAddress; 
    webclient.Credentials = new NetworkCredential(username, password); 

    webclient.UploadFile(ftpPath + fileName + ".pdf", localFilePath); 
} 
+1

您是否看到該問題? http://stackoverflow.com/a/9738609/1346943 –

+0

@ledbutter當我使用webclient上傳文件時,我收到消息「遠程服務器返回錯誤:(553)文件名不允許。」 –

+0

什麼是文件名? – Tony

回答

2

你的方法upload最有可能打破PDF內容,因爲它將其視爲文本:

您使用StreamReader來閱讀PDF文件。這個類

Implements a TextReader that reads characters from a byte stream in a particular encoding.

(MSDN StreamReader information)

這意味着,在讀取文件的字節,該類根據該特定的編碼(UTF-8,你的情況,因爲這是默認的)解釋它們。但並不是所有的字節組合都可以用作UTF-8字符組合。因此,這種閱讀已經具有破壞性。

你部分彌補這種解釋通過再編碼的字符根據UTF-8後:

byte[] fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd()); 

但正如前面所說的,初始解釋,解碼作爲已經是UTF-8編碼的文件已經銷燬了原始文件,除非您足夠幸運,並且所有字節組合都以UTF-8編碼文本的形式表現出來。

對於二進制數據(如ZIP壓縮文件,Word文檔或PDF文件),您應該使用FileStream類,參見參考資料。 its MSDN information

+0

好吧,我知道它與FileStream一起工作!謝謝(你的)信息 :) –