我正在创建一个简单的拖动文件和上传自动到ftp的Windows应用程序
我正在使用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,在FTP中(以及下载后),它有219Kb ......
我做错了什么?
顺便说一句,uploadFileToFTP()
方法在BackgroundWorker
内运行,但我真的没有任何区别......
答案 0 :(得分:32)
您不应该使用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());
}
}
答案 1 :(得分:3)
问题是由您的代码将二进制数据解码为字符数据并返回二进制数据引起的。不要这样做。
使用UploadFile Method的WebClient Class:
using (WebClient client = new WebClient())
{
client.Credentials = new NetworkCredential(FTP_USR, FTP_PWD);
client.UploadFile(FTP_PATH + filenameToUpload, filenameToUpload);
}