2014-09-21 105 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(); 
    } 
相关问题