我在FTP服务器上收到一个文件,该文件的名称是动态生成的。我试图编写一个程序来检查服务器上是否存在任何文件。
string userName = Dts.Variables["User::SFTPUsername"].Value.ToString();
string password = Dts.Variables["User::SFTPPassword"].Value.ToString();
**string fileName = Dts.Variables["User::FilePattern"].Value.ToString();**
string ftpURL = String.Format("ftp://11.11.11/upload/{0}", fileName);
WebClient request = new WebClient();
request.Credentials = new NetworkCredential(userName, password);
FtpWebRequest ftpRequest = (FtpWebRequest)WebRequest.Create(ftpURL);
ftpRequest.Method = WebRequestMethods.Ftp.GetFileSize;
ftpRequest.Credentials = new NetworkCredential(userName, password);
using (FtpWebResponse ftpResponse = (FtpWebResponse)ftpRequest.GetResponse())
{
byte[] newFileData = request.DownloadData(ftpURL.ToString());
string fileString = System.Text.Encoding.UTF8.GetString(newFileData);
string strexist = String.Format("exist");
MessageBox.Show(strexist);
Dts.Variables["User::FileExists"].Value = true;
}
仅当我指定“ fileName”时,此方法才能很好地工作。无论如何,我可以进行通配符搜索(“ * .txt”)还是可以搜索上传文件夹中是否有文件?
任何帮助表示赞赏!
您可以从中列出文件名FTP
。像下面...
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftpURL);
request.Method = WebRequestMethods.Ftp.ListDirectory;
FtpWebResponse response = (FtpWebResponse) request.GetResponse();
using (Stream respStream = response.GetResponseStream())
{
StreamReader reader = new StreamReader(respStream);
//Read each file name from the response
for (string fname = reader.ReadLine(); fname != null; fname = reader.ReadLine())
{
// Add the file name into a list
}
}
如果列表计数为0,则没有文件可用。同样,您将从单个请求中获得列表中的每个文件名。
使用迭代列表值foreach loop
。并将上述代码作为方法。将文件名传递给方法。
您也可以确保列表中存在或不存在特定的文件名。
注:在上面的代码没有需要提供的文件名的网址。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句