我创建一个简单的拖放文件和上传,自动对FTP的Windows应用程序将文件上传到FTP目的地
被破坏一次,我使用MSDN code到将文件上传到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 lenght并在FTP(和下载后),它拥有219KB ...
我在做什么错?
顺便说一句,该uploadFileToFTP()
方法是BackgroundWorker
内运行,但我真的不使任何差异的事情...
二进制数据和UTF-8不拌匀。 – dtb 2012-04-26 09:28:40
@dtb使用'Encoding.ASCII.GetBytes(sourceStream.ReadToEnd());'得到相同的行为... – balexandre 2012-04-26 09:30:32
感叹。 **二进制**数据和**字符**数据是两个不同的东西。是的,您可以将字符编码为字节,但不能盲目解码不编码字符的字节。 – dtb 2012-04-26 09:32:03