2015-10-13 70 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服务器应该不会令人惊讶。