Reputation: 2146
Here is the Solution ,thanks Gustavo for the suggestion:
class Program
{
static void Main(string[] args)
{
ConsoleApplication1.Program test = new Program();
string Name = "SE_TEST";
string[] filteredfiles = test.GetFileList();
string[] files = filteredfiles;
foreach (string file in files)
{
bool b;
if (b = file.Contains(Name))
{
test.Download(file);
}
}
}
public string[] GetFileList()
{
string[] downloadFiles;
StringBuilder result = new StringBuilder();
WebResponse response = null;
StreamReader reader = null;
try
{
FtpWebRequest reqFTP;
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + "1.0.0.1" + "/"));
reqFTP.UseBinary = true;
reqFTP.Credentials = new NetworkCredential("sh", "SE");
reqFTP.Method = WebRequestMethods.Ftp.ListDirectory;
reqFTP.Proxy = null;
reqFTP.KeepAlive = false;
reqFTP.UsePassive = false;
response = reqFTP.GetResponse();
reader = new StreamReader(response.GetResponseStream());
string line = reader.ReadLine();
while (line != null)
{
result.Append(line);
result.Append("\n");
line = reader.ReadLine();
}
// to remove the trailing '\n'
result.Remove(result.ToString().LastIndexOf('\n'), 1);
return result.ToString().Split('\n');
}
catch (Exception ex)
{
if (reader != null)
{
reader.Close();
}
if (response != null)
{
response.Close();
}
downloadFiles = null;
return downloadFiles;
}
}
private void Download(string file)
{
try
{
FtpWebRequest reqFTP;
string ftpserverIp = "1.0.0.1";
string fileName = @"c:\downloadDir\" + file;
FileInfo downloadFile = new FileInfo(fileName);
// string uri = "ftp://1.0.0.1";
FileStream outputStream = new FileStream(fileName, FileMode.Append);
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + ftpserverIp + "/" + file));
reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
reqFTP.UseBinary = true;
reqFTP.KeepAlive = false;
reqFTP.Timeout = -1;
reqFTP.UsePassive = true;
reqFTP.Credentials = new NetworkCredential("sh", "SE");
FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
Stream ftpStream = response.GetResponseStream();
long cl = response.ContentLength;
// reqFTP.Method = WebRequestMethods.Ftp.ListDirectory;
int bufferSize = 4096;
int readCount;
byte[] buffer = new byte[bufferSize];
readCount = ftpStream.Read(buffer, 0, bufferSize);
Console.WriteLine("Connected: Downloading File");
while (readCount > 0)
{
outputStream.Write(buffer, 0, readCount);
readCount = ftpStream.Read(buffer, 0, bufferSize);
Console.WriteLine(readCount.ToString());
}
ftpStream.Close();
outputStream.Close();
response.Close();
Console.WriteLine("Downloading Complete");
}
catch (Exception ex)
{
Console.Write(ex);
}
}
}
}
It works as expected but not sure about the performance,is this any better way to do please suggest.Anyway thanks for your suggestion
Upvotes: 2
Views: 3324
Reputation: 2206
List all files with the method:
WebRequestMethods.Ftp.ListDirectoryDetails
Filter FileNames with Contains()
Download ALL the Files that Contains your string.
Upvotes: 3