2014-07-10 17 views
0

目前我從本地機上傳csv文件作爲輸入到我的方法,它將數據插入到sql表中。如何直接從FTP上傳csv文件,並將其作爲c#中的輸入內容?

我這樣做像

[system.web.mvc.httppost] 
public actionresult Uploadfile(HttpPostedFileBase file) 
{ 
//} 

現在我試着上傳從FTP位置的文件會自動使用下面的代碼

但我怎麼可以整合這跟我的老上述方法的任何猜測?

string _ftpURL = "testftp.com";    //Host URL or address of the FTP server 
string _UserName = "admin";     //User Name of the FTP server 
string _Password = "admin123";    //Password of the FTP server 
string _ftpDirectory = "Receipts";   //The directory in FTP server where the files are present 
string _FileName = "test1.csv";    //File name, which one will be downloaded 
string _LocalDirectory = "D:\\FilePuller"; //Local directory where the files will be downloaded 
DownloadFile(_ftpURL, _UserName, _Password, _ftpDirectory, _FileName, _LocalDirectory); 

public void DownloadFile(string ftpURL, string UserName, string Password, string ftpDirectory, string FileName, string LocalDirectory) 
{ 
    if (!File.Exists(LocalDirectory + "/" + FileName)) 
    { 
     try 
     { 
      FtpWebRequest requestFileDownload = (FtpWebRequest)WebRequest.Create(ftpURL + "/" + ftpDirectory + "/" + FileName); 
      requestFileDownload.Credentials = new NetworkCredential(UserName, Password); 
      requestFileDownload.Method = WebRequestMethods.Ftp.DownloadFile; 
      FtpWebResponse responseFileDownload = (FtpWebResponse)requestFileDownload.GetResponse(); 
      Stream responseStream = responseFileDownload.GetResponseStream(); 
      FileStream writeStream = new FileStream(LocalDirectory + "/" + FileName, FileMode.Create); 
      int Length = 2048; 
      Byte[] buffer = new Byte[Length]; 
      int bytesRead = responseStream.Read(buffer, 0, Length); 
      while (bytesRead > 0) 
      { 
       writeStream.Write(buffer, 0, bytesRead); 
       bytesRead = responseStream.Read(buffer, 0, Length); 
      } 
      responseStream.Close(); 
      writeStream.Close(); 
      requestFileDownload = null; 
     } 
     catch (Exception ex) 
     { 
      throw ex; 
     } 
    } 
} 
+1

你的問題並不十分清楚,但看起來你只需要首先從你的FTP服務器獲取CSV文件,將它存儲在本地,然後像你一直在做的那樣發送它。又是什麼問題? –

回答

1

不是100%清楚我已經正確理解了這一點,但您可以簡單地從您的Controller Action調用DownloadFile方法。你有沒有在這裏提及的命名空間/類,所以就需要像

FTPHelper FTP = new FTPHelper(); 
FTP.DownloadloadFile("TestFTP.com etc etc etc......); 

您需要考慮如果FTP細節硬編碼或更換。無論你想在行動中加入安全性,還是每次都要將文件調用相同的東西,很容易對此進行參數化,但我原以爲你可能需要加強FTP服務器來獲取那裏的東西,而不是知道名稱。這裏也沒有自動化,還需要調用動作來啓動它。

如果你能澄清你的問題多一點,我可以嘗試和更具體。

相關問題