I receive a file on the FTP server, the name of the file is generated dynamically. I am trying to write a program to check if any file exists on the server.
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;
}
This works well only when I specify the "fileName". Is there anyway I can do a wildcard search ("*.txt") or search if anyfile is in the upload folder?
Any help appreciated!!
There sure is!
Try setting
ftpURL
to the directory name in question andrequest.Method
toWebRequestMethods.Ftp.ListDirectory;
.For examples, check out http://timtrott.co.uk/ultimate-guide-ftp/ and http://msdn.microsoft.com/en-us/library/ms229716%28v=vs.110%29.aspx (note: the latter uses
WebRequestMethods.Ftp.ListDirectoryDetails
instead ofListDirectory
, so you may need to slightly modify it).You can list out the file names from the
FTP
. Like Below...If the list count is 0 then there is no file available. Also you will get the each file name in a list from the single request.
Iterate the list values using
foreach loop
. And make the above code as a method. Pass the File name to the method.You can also do make sure particular file name is exists or not in the list.
Note: In the above code no need to provide the file name to the Url.