我有一个简单的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;
}
}
答案 0 :(得分:2)
Stream.Read
不保证您读取所请求的所有字节。
具体而言FileStream.Read
documentation说:
count:最大要读取的字节数 返回值:读入缓冲区的总字节数。如果当前没有该字节数,则可能可能小于,如果到达流末尾则为零
。
要将整个文件读取到内存,请使用File.ReadAllBytes
:
byte[] buffer = File.ReadAllBytes(source);
虽然您实际上应该使用Stream.CopyTo
,但要避免将大量文件完全存储到内存中:
fs.CopyTo(ftp.GetRequestStream());
答案 1 :(得分:0)
不确定您遇到了什么问题。
这段代码对我来说很合适:
String sourcefilepath = "";
String ftpurl = ""; // e.g. ftp://serverip/foldername/foldername
String ftpusername = ""; // e.g. username
String ftppassword = ""; // e.g. password
var filePath = "";
try
{
string filename = Path.GetFileName(sourcefilepath);
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;
byte[] buffer = File.ReadAllBytes(sourcefilepath);
ftp.ContentLength = buffer.Length;
Stream ftpstream = ftp.GetRequestStream();
ftpstream.Write(buffer, 0, buffer.Length);
ftpstream.Close();
}
catch (Exception ex)
{
throw ex;
}