我如何从FTP直接上传csv文件,这将是在c#输入
本文关键字:文件 输入 csv FTP | 更新日期: 2023-09-27 18:12:25
目前我正在上传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服务器以获取那里的内容,而不是知道名称。这里也没有自动化,仍然需要调用动作来启动它。