2015-10-13 48 views
-1

FTP我想從本地上傳文件(字節= 2000)到FTP服務器,但finnaly我finda空文件(0字節)如何上傳文件使用C#

public void upload(string remoteFile, string localFile) 
{ 
    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 = true; 
     ftpRequest.UsePassive = true; 
     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 */ 
     //int bytesRead; 
     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; 
} 
+0

當我調試我發現bytesSent = 0和byteBuffer = 2000 – kaliliP

+1

「/ *打開一個文件流*讀*文件上傳* /」評論不符合它旁邊的代碼。發佈前請務必查看您的代碼。另外考慮使用'Stream.CopyTo' ... –

+0

from web config: kaliliP

回答

2

您使用FileMode.Create打開本地文件;然而,作爲MSDN documentation狀態,FileMode.Create

指定操作系統應創建一個新的文件。如果 文件已經存在,它將被覆蓋。這需要 FileIOPermissionAccess.Write權限。 FileMode.Create等價於 要求如果該文件不存在,請使用CreateNew; 否則,請使用截斷。如果該文件已存在但是隱藏文件 ,則引發UnauthorizedAccessException異常。

因此,您正在讀取的是零字節文件;在這種情況下,將零字節發送到FTP服務器應該不會令人驚訝。