【发布时间】:2017-06-15 15:26:26
【问题描述】:
我有一个简单的 FTP 上传器(大部分不是我自己的代码,还在学习中) 它工作得很好,但它正在破坏 exe 文件,从我的阅读来看,这是因为它不是二进制阅读器。但令人困惑的是我告诉它使用二进制文件。
这是我的代码:
private void UploadFileToFTP(string source)
{
String sourcefilepath = textBox5.Text;
String ftpurl = textBox3.Text; // e.g. ftp://serverip/foldername/foldername
String ftpusername = textBox1.Text; // e.g. username
String ftppassword = textBox2.Text; // e.g. password
try
{
string filename = Path.GetFileName(source);
string ftpfullpath = ftpurl + "/" + new FileInfo(filename).Name;
FtpWebRequest ftp = (FtpWebRequest)FtpWebRequest.Create(ftpfullpath);
ftp.Credentials = new NetworkCredential(ftpusername, ftppassword);
ftp.KeepAlive = true;
ftp.UseBinary = true;
ftp.Method = WebRequestMethods.Ftp.UploadFile;
FileStream fs = File.OpenRead(source);
byte[] buffer = new byte[fs.Length];
fs.Read(buffer, 0, buffer.Length);
fs.Close();
Stream ftpstream = ftp.GetRequestStream();
ftpstream.Write(buffer, 0, buffer.Length);
ftpstream.Close();
}
catch (Exception ex)
{
throw ex;
}
}
【问题讨论】:
-
你是什么意思它工作正常但损坏 exe 文件?如果它损坏文件,它如何正常工作?
-
因为上传的实际功能适用于大多数文件类型。除了 .exes
-
那么听起来像是编码问题。也许 OpenRead() 对编码做了一些时髦的事情。试试我下面的例子。我刚刚用 EXE 测试了它,它运行良好。
标签: c# .net ftp binary ftpwebrequest