簡體   English   中英

如何直接從FTP上傳csv文件,該文件將作為c#中的輸入?

[英]How do I upload csv file from FTP directly which will be as input in c#?

目前,我正在從本地計算機上傳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;
        }
    }
}

並非100%清楚,我已經正確理解了這一點,但是您可以直接從Controller Action中調用DownloadFile方法。 您在這里沒有提到名稱空間/類,因此需要類似

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

您需要考慮FTP詳細信息是否經過硬編碼或可更改。 是否要在操作周圍合並安全性以及是否每次都將文件稱為同一事物,非常容易將其參數化,但是我認為您可能需要加強FTP服務器以獲取那里的內容,而不是知道名稱。 這里也沒有自動化,仍然需要調用操作來啟動它。

如果您可以進一步澄清您的問題,我可以嘗試並更加具體。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM