如何直接从FTP上传csv文件,这将作为c#的输入?

时间:2014-07-10 15:47:13

标签: c# asp.net-mvc string asp.net-mvc-3 csv

目前我正在将本地计算机上的csv文件作为输入上传到我的方法,该方法会将数据插入到sql表中。

我这样做

[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 个答案:

答案 0 :(得分:1)

不是100%清楚我已正确理解这一点,但您只需从Controller Action中调用DownloadFile方法即可。你没有在这里提到名称空间/类,所以需要像

这样的东西
FTPHelper FTP = new FTPHelper();
FTP.DownloadloadFile("TestFTP.com etc etc etc......);

您需要考虑FTP详细信息是硬编码还是可更改的。是否要在操作周围加入安全性,以及每次调用文件是否相同,非常容易参数化,但我认为您可能需要使用FTP服务器来获取那里的内容而不是知道名称。这里也没有自动化,仍然需要调用动作来启动它。

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