So Im trying to upload a file to my ftp server. Every things seems to work like expected but when I open the file from from the ftp I receive a I/O error. The local file works just fine. Some how the file gets corrupt after uploading. I found a similar problem here.

Here I read that you have to change the transfer mode to binary. I tried to set ftpRequest.UseBinary = true; But I still get the I/O error. Do I have to change the transfer mode somewhere els?

This is my ftp upload code:

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);
}

Using webclient I get the error:

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

Here is my code:

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);
}
有帮助吗?

解决方案

Your method upload most likely breaks the PDF contents because it treats it as text:

You use a StreamReader to read the PDF file. That class

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

(MSDN StreamReader information)

This implies that while reading the file bytes, the class interprets them according to that particular encoding (UTF-8 in your case because that's the default). But not all byte combinations do make sense as UTF-8 character combinations. Thus, this reading already is destructive.

You partially make up for this interpretation by re-encoding the characters according to UTF-8 later:

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

but as said before, the initial interpretation, the decoding as a UTF-8 encoded file already has destroyed the original file unless you were lucky enough and all the byte combinations made sense as UTF-8 encoded text.

For binary data (like ZIP archives, Word documents or PDF files) you should use the FileStream class, cf. its MSDN information.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top