上传到 ftp 后打开 pdf 时出现 I/O 错误

问题描述 投票:0回答:2

所以我尝试将文件上传到我的 ftp 服务器。一切似乎都按预期工作,但是当我从 ftp 打开文件时,我收到一个 I/O 错误。本地文件工作得很好。一些文件上传后如何损坏的情况。我发现了类似的问题here

我在这里读到您必须将传输模式更改为二进制。我尝试设置

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

使用网络客户端时出现错误:

远程服务器返回错误:(553) 文件名不允许。

这是我的代码:

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);
}
c# pdf ftpwebrequest ioerror
2个回答
2
投票

您的方法

upload
很可能会破坏PDF内容,因为它将其视为文本:

您可以使用

StreamReader
来阅读 PDF 文件。那个班

实现一个 TextReader,以特定编码从字节流中读取字符。

(MSDN StreamReader 信息)

这意味着在读取文件字节时,该类会根据该特定编码(在您的情况下为UTF-8,因为这是默认值)来解释它们。但并非所有字节组合都作为 UTF-8 字符组合有意义。因此,这种阅读已经具有破坏性。

您可以通过稍后根据 UTF-8 重新编码字符来部分弥补这种解释:

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

但正如之前所说,最初的解释是,解码为 UTF-8 编码文件已经破坏了原始文件,除非您足够幸运并且所有字节组合都作为 UTF-8 编码文本有意义。

对于二进制数据(如 ZIP 档案、Word 文档或 PDF 文件),您应该使用

FileStream
类,参见。 其 MSDN 信息


0
投票

Ainda não encontrei a solução para o código que estou fazendo

© www.soinside.com 2019 - 2024. All rights reserved.