c# - 使用 ftpwebrequest 上传到 ftp 时图像损坏

标签 c# ftp

我使用此代码将图像上传到 ftp。但图像已损坏。 我尝试上传的图像是 Base64 字符串。我将其转换为流并将其传递给 UpLoadImage。

 public static void UpLoadImage(Stream image, string target)
   {
    FtpWebRequest req = (FtpWebRequest)WebRequest.Create("ftp://www.examp.com/images/" + target);
    req.UseBinary = true;
    req.Method = WebRequestMethods.Ftp.UploadFile;
    req.Credentials = new NetworkCredential("UserNm", "PassWd");
    StreamReader rdr = new StreamReader(image);
    byte[] fileData = Encoding.UTF8.GetBytes(rdr.ReadToEnd());
    rdr.Close();
    req.ContentLength = fileData.Length;
    Stream reqStream = req.GetRequestStream();
    reqStream.Write(fileData, 0, fileData.Length);
    reqStream.Close();
}

代替:

StreamReader rdr = new StreamReader(image); byte[] fileData = Encoding.UTF8.GetBytes(rdr.ReadToEnd()); rdr.Close();

如果我使用 byte[] fileData = File.ReadAllBytes(image); 它给了我一个错误,文件名超过了 260 个字符。

请有人帮忙解决这个问题..

最佳答案

点赞评论说 使用

byte[] fileData = File.ReadAllBytes(filePath);

对于所有不是文本文件的文件。

像那样:

private void FTPUPLOAD(string imgPath)
        {
            FTPDelete(img);
            // Get the object used to communicate with the server.
            FtpWebRequest request = (FtpWebRequest)WebRequest.Create(BaseUrl +Path.GetFileName(imgPath));
            request.Method = WebRequestMethods.Ftp.UploadFile;

            // This example assumes the FTP site uses anonymous logon.
            request.Credentials = new NetworkCredential(Account, Password);

            // Copy the contents of the file to the request stream.
             //THIS IS THE CODE
            byte[] fileContents = File.ReadAllBytes(imgPath);

 Stream requestStream = request.GetRequestStream();
            requestStream.Write(fileContents, 0, fileContents.Length);
            requestStream.Close();

            FtpWebResponse response = (FtpWebResponse)request.GetResponse();

            response.Close();
        }

关于c# - 使用 ftpwebrequest 上传到 ftp 时图像损坏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15826149/

相关文章:

c# - 如何将 Microsoft.OneDriveSDK v1 迁移到 v2?

c# - 处理并发

linux - 在 Linux 上使用 PSFTP

.net - 是否可以通过 WebRequest 使用的 Windows/网络凭据来访问本地文件夹而不是单元测试中的远程 FTP?

c# - WCF ServiceHost 访问权限

c# - VS 2010 类图 - 可以删除按字母顺序排序吗?

c# - Unity 中的缩放问题

upload - FTP 传输在每行代码后添加空格

C# FTP 不支持给定路径的格式

c# - 无法对 FTP 文件夹使用 GetDateTimestamp