C# FTP服务器上传文件成功但文件损坏,求代码问题排查及修复
问题根因
你怀疑的代码行确实是问题核心:
StreamReader是文本读取器,仅适合读取UTF8、ASCII等编码的纯文本文件,会自动对二进制字节做文本解码转换,读取图片、音视频、压缩包等非文本文件时,会把无法识别的字节替换为错误字符,最终转成的fileContents字节数组和原文件二进制内容完全不一致,导致文件损坏。- 额外冗余问题:你重复给
request.Method赋值了两次WebRequestMethods.Ftp.UploadFile,属于无效代码。
修复后完整代码
string ftpurl = "ftp://IP"; string ftpusername = "u09z0fyuu"; string ftppassword = "Yamankatita1@"; string PureFileName = new FileInfo(file_name).Name; string uploadUrl = String.Format("{0}/{1}/{2}", ftpurl, "PDPix", file_name); FtpWebRequest request = (FtpWebRequest)FtpWebRequest.Create(uploadUrl); request.Method = WebRequestMethods.Ftp.UploadFile; request.Credentials = new NetworkCredential(ftpusername, ftppassword); request.Proxy = null; request.KeepAlive = true; request.UseBinary = true; request.UsePassive = true; // 修复:直接读取文件原始二进制字节,不做文本编码转换 byte[] fileContents = File.ReadAllBytes(_mediaFile.Path); request.ContentLength = fileContents.Length; // 推荐用using自动释放流资源,避免手动Close漏写的风险 using (Stream requestStream = request.GetRequestStream()) { requestStream.Write(fileContents, 0, fileContents.Length); } using (FtpWebResponse response = (FtpWebResponse)request.GetResponse()) { _ = DisplayAlert("上传文件完成,状态:{0}", response.StatusDescription, "OK"); }
大文件场景优化建议
如果上传的是几百MB以上的大文件,不需要把整个文件读入内存,可以直接做流拷贝降低内存占用:
using (FileStream fs = File.OpenRead(_mediaFile.Path)) using (Stream requestStream = request.GetRequestStream()) { request.ContentLength = fs.Length; fs.CopyTo(requestStream); }
内容的提问来源于stack exchange,提问作者Zikria Rasul
相关产品推荐
相关产品推荐

