2014-09-21 76 views
-1

我需要使用c#從本地機器上傳文本文件到ftp服務器。 我試過folowing代碼,但它沒有工作。如何使用c#.net將本地計算機上的許多文本文件上傳到ftp?

private bool UploadFile(FileInfo fileInfo) 
{ 
    FtpWebRequest request = null; 
    try 
    { 
     string ftpPath = "ftp://www.tt.com/" + fileInfo.Name 
     request = (FtpWebRequest)WebRequest.Create(ftpPath); 
     request.Credentials = new NetworkCredential("ftptest", "ftptest"); 
     request.Method = WebRequestMethods.Ftp.UploadFile; 
     request.KeepAlive = false; 
     request.Timeout = 60000; // 1 minute time out 
     request.ServicePoint.ConnectionLimit = 15; 

     byte[] buffer = new byte[1024]; 
     using (FileStream fs = new FileStream(fileInfo.FullPath, FileMode.Open)) 
     { 
      int dataLength = (int)fs.Length; 
      int bytesRead = 0; 
      int bytesDownloaded = 0; 
      using (Stream requestStream = request.GetRequestStream()) 
      { 
       while (bytesRead < dataLength) 
       { 
        bytesDownloaded = fs.Read(buffer, 0, buffer.Length); 
        bytesRead = bytesRead + bytesDownloaded; 
        requestStream.Write(buffer, 0, bytesDownloaded); 
       } 
       requestStream.Close(); 
      } 
     } 
     return true; 
    } 
    catch (Exception ex) 
    { 
     throw ex;     
    } 
    finally 
    { 
     request = null; 
    } 
    return false; 
}// UploadFile 

任何建議???

+1

** **是如何工作的?它爆炸了嗎? – SLaks 2014-09-21 12:26:08

+3

你的'try'塊完全沒用,並且破壞了異常棧的蹤跡。 – SLaks 2014-09-21 12:26:49

回答

0

您需要通過致電GetResponse()實際發送請求。

您還可以通過撥打fs.CopyTo(requestStream)使代碼更加簡單。

0

我用一些ftp代碼修飾了下面的內容,這對我來說似乎很好。

ftpUploadlocftp://ftp.yourftpsite.com/uploaddir/yourfilename.txt

ftpUsernameftpPassword應該是自解釋。

最後currentLog是您上傳文件的位置。

讓我知道這是如何解決你的,如果任何人有任何其他建議,我歡迎這些。

private void ftplogdump() 
    { 
     FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftpUploadloc); 
     request.Method = WebRequestMethods.Ftp.UploadFile; 
     request.Credentials = new NetworkCredential(ftpUsername, ftpPassword); 
     StreamReader sourceStream = new StreamReader(currentLog); 
     byte[] fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd()); 
     sourceStream.Close(); 
     request.ContentLength = fileContents.Length; 

     Stream requestStream = request.GetRequestStream(); 
     requestStream.Write(fileContents, 0, fileContents.Length); 
     requestStream.Close(); 

     FtpWebResponse response = (FtpWebResponse)request.GetResponse(); 


     // Remove before publishing 
     Console.WriteLine("Upload File Complete, status {0}", response.StatusDescription); 

     response.Close(); 
    } 
相關問題