2017-06-15 31 views
1

我有一个简单的FTP上传(大多不是我自己的代码,仍在学习) 它工作得很好,但它正在破坏EXE文件,从我的阅读周围,这是因为它不是一个二进制阅读器。但令人困惑的是,我正在告诉它使用二进制。FTP FtpWebRequest uploader腐败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

怎么办你的意思是它工作正常,但腐败exe文件?它是如何正常工作,如果它是破坏文件? –

+0

因为上传的实际功能适用于大多数文件类型。除了.exes –

+0

然后听起来像是一个编码问题。也许OpenRead()对编码做一些简单的事情。试试我的例子。我只用EXE测试过,它工作正常。 – Cory

回答

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; 
} 
+0

我用过这个,但它仍然有效。感谢一群兄弟: byte [] buffer = new byte [fs.Length]; fs.Read(buffer,0,buffer.Length); ftp.ContentLength = fs.Length; fs.Close(); –

+0

尴尬..:| 。我不知道。感谢您的链接。 – Cory

2

Stream.Read并不能保证你念你所要求的所有字节。

具体FileStream.Read documentation说:

计数:要读取的最大字节数。
返回值:读入缓冲区的总字节数。如果该字节数当前不可用,则该可能比请求的字节数少,或者如果到达流的末尾则为零。


要读取整个文件到内存,使用File.ReadAllBytes

byte[] buffer = File.ReadAllBytes(source); 

虽然你应该实际使用Stream.CopyTo,完全避免存储大文件到内存:

fs.CopyTo(ftp.GetRequestStream());