2013-10-31 381 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一起工作!谢谢(你的)信息 :) –