Reputation: 357
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!!
Upvotes: 1
Views: 4290
Reputation: 6461
You can list out the file names from the FTP
. Like Below...
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
}
}
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.
Upvotes: 2
Reputation: 5147
There sure is!
Try setting ftpURL
to the directory name in question and request.Method
to WebRequestMethods.Ftp.ListDirectory;
.
var request = (FtpWebRequest)WebRequest.Create("ftp://www.example.com/uploads");
request.Method = WebRequestMethods.Ftp.ListDirectory;
request.Credentials = new NetworkCredential(userName, password);
using (FtpWebResponse ftpResponse = (FtpWebResponse)ftpRequest.GetResponse())
{
...
}
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 of ListDirectory
, so you may need to slightly modify it).
Upvotes: 2