我正在创建一个简单的拖动文件并自动上传到 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...
What am I doing wrong?
顺便说一句,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());
}
}
关于c# - 上传到 FTP 的文件一旦到达目的地就会损坏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10330641/