2015-11-18 92 views
1

形勢FTP上傳0字節

我有一些代碼,在這種情況下上傳一個文件,通常的.csv到遠程FTP站點

代碼

try 
    { 
     /* Create an FTP Request */ 
     ftpRequest = (FtpWebRequest)FtpWebRequest.Create(host + "/" + remoteFile); 
     /* Log in to the FTP Server with the User Name and Password Provided */ 
     ftpRequest.Credentials = new NetworkCredential(user, pass); 
     /* When in doubt, use these options */ 
     ftpRequest.UseBinary = false; 
     ftpRequest.UsePassive = false; 
     ftpRequest.KeepAlive = true; 
     /* Specify the Type of FTP Request */ 
     ftpRequest.Method = WebRequestMethods.Ftp.UploadFile; 
     /* Establish Return Communication with the FTP Server */ 
     ftpStream = ftpRequest.GetRequestStream(); 
     /* Open a File Stream to Read the File for Upload */ 
     FileStream localFileStream = new FileStream(localFile, FileMode.Create); 
     /* Buffer for the Downloaded Data */ 
     byte[] byteBuffer = new byte[bufferSize]; 
     int bytesSent = localFileStream.Read(byteBuffer, 0, bufferSize); 
     /* Upload the File by Sending the Buffered Data Until the Transfer is Complete */ 
     try 
     { 
      while (bytesSent != 0) 
      { 
       ftpStream.Write(byteBuffer, 0, bytesSent); 
       bytesSent = localFileStream.Read(byteBuffer, 0, bufferSize); 
      } 
     } 
     catch (Exception ex) { Console.WriteLine(ex.ToString()); } 
     /* Resource Cleanup */ 
     localFileStream.Close(); 
     ftpStream.Close(); 
     ftpRequest = null; 
    } 
    catch (Exception ex) { Console.WriteLine(ex.ToString()); } 
    return; 
} 

問題

該程序使連接成功並且似乎上傳我的文件,但.csv爲空,文件大小爲0字節。我的代碼中是否有可能導致此問題的任何內容?

+2

你的緩衝區大小是多少? –

+0

緩衝區大小爲2048 –

回答

4

您是否發現本地文件被截斷爲0字節?我認爲這個問題是在這裏:

FileStream localFileStream = new FileStream(localFile, FileMode.Create); 

你應該FileMode.OpenFileMode.OpenOrCreate來打開該文件。 documentation for FileMode.Create指出「如果文件已經存在,它將被覆蓋。」和「FileMode.Create相當於請求如果文件不存在,請使用CreateNew;否則,使用截斷」。

+0

這就是我正要寫的東西 - 爲您的快速響應而讚歎! –

+0

是的本地文件也被截斷只是注意到,謝謝我會試試這個。 –

+0

太棒了,我現在覺得有點蠢。 –