将文件上传到FTP在目标中已损坏一次
我正在创建一个简单的drag-file-and-upload-automatic-to-ftp windows应用程序
我正在使用MSDN代码将文件上传到FTP。
代码很简单:
// Get the object used to communicate with the server. FtpWebRequest request = (FtpWebRequest)WebRequest.Create(String.Format("{0}{1}", FTP_PATH, filenameToUpload)); request.Method = WebRequestMethods.Ftp.UploadFile; // Options request.UseBinary = true; request.UsePassive = false; // FTP Credentials request.Credentials = new NetworkCredential(FTP_USR, FTP_PWD); // Copy the contents of the file to the request stream. StreamReader sourceStream = new StreamReader(fileToUpload.FullName); byte[] fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd()); sourceStream.Close(); request.ContentLength = fileContents.Length; Stream requestStream = request.GetRequestStream(); requestStream.Write(fileContents, 0, fileContents.Length); requestStream.Close(); FtpWebResponse response = (FtpWebResponse)request.GetResponse(); writeOutput("Upload File Complete!"); writeOutput("Status: " + response.StatusDescription); response.Close();
它确实上传到FTP
问题是当我在浏览器上看到该文件,或者只是下载并尝试在桌面上看到它时,我得到:
我已经使用了request.UseBinary = false;
和request.UsePassive = false;
但它并不能做任何好事。
我发现的是,原始文件有122Kb长度,在FTP(和下载后),它有219Kb …
我究竟做错了什么?
顺便说一句, uploadFileToFTP()
方法在BackgroundWorker
运行,但我真的没有任何区别……
您不应该使用StreamReader而只能使用Stream来读取二进制文件。
Streamreader仅用于读取文本文件。
试试这个:
private static void up(string sourceFile, string targetFile) { try { string ftpServerIP = ConfigurationManager.AppSettings["ftpIP"]; string ftpUserID = ConfigurationManager.AppSettings["ftpUser"]; string ftpPassword = ConfigurationManager.AppSettings["ftpPass"]; ////string ftpURI = ""; string filename = "ftp://" + ftpServerIP + "//" + targetFile; FtpWebRequest ftpReq = (FtpWebRequest)WebRequest.Create(filename); ftpReq.UseBinary = true; ftpReq.Method = WebRequestMethods.Ftp.UploadFile; ftpReq.Credentials = new NetworkCredential(ftpUserID, ftpPassword); byte[] b = File.ReadAllBytes(sourceFile); ftpReq.ContentLength = b.Length; using (Stream s = ftpReq.GetRequestStream()) { s.Write(b, 0, b.Length); } FtpWebResponse ftpResp = (FtpWebResponse)ftpReq.GetResponse(); if (ftpResp != null) { MessageBox.Show(ftpResp.StatusDescription); } } catch (Exception ex) { MessageBox.Show(ex.ToString()); } }
问题是由您的代码将二进制数据解码为字符数据并返回二进制数据引起的。 不要这样做。
使用WebClient类的UploadFile方法 :
using (WebClient client = new WebClient()) { client.Credentials = new NetworkCredential(FTP_USR, FTP_PWD); client.UploadFile(FTP_PATH + filenameToUpload, filenameToUpload); }