2014-07-10 16 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服务器来获取那里的东西,而不是知道名称。这里也没有自动化,还需要调用动作来启动它。

如果你能澄清你的问题多一点,我可以尝试和更具体。

相关问题