
Yazimin ikinci kismiyla tekrar merhaba.. Ilk bolumde verilen bir ftp klasoru altindaki dosyalarin listesini aliyorduk. Bu yazimda ise herhangi bir dosyayi ya da butun klasoru nasil download edebiliriz konusunu islemeye calisacagim. Download folder icin bir onceki yazimda yer alan GetFileList metodunu kullanacagiz. Neyse sozu fazla uzatmadan biraz kod gorelim.
public static void Download(string file, string remoteDirectory, string destinationDirectory, string host, string user, string password)
{
try
{
string uri = "ftp://" + host + "/" + remoteDirectory + "/" + file;
Uri serverUri = new Uri(uri);
if (serverUri.Scheme != Uri.UriSchemeFtp)
{
return;
}
FtpWebRequest reqFTP;
reqFTP = (FtpWebRequest)FtpWebRequest.Create(serverUri);
reqFTP.Credentials = new NetworkCredential(user, password);
reqFTP.KeepAlive = false;
reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
reqFTP.UseBinary = true;
reqFTP.Proxy = null;
reqFTP.UsePassive = false;
FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
Stream responseStream = response.GetResponseStream();
CreateDirectory(destinationDirectory);
FileStream writeStream = new FileStream(destinationDirectory + "\\" + file, 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);
}
writeStream.Close();
response.Close();
}
catch (WebException wEx)
{
throw wEx;
}
catch (Exception ex)
{
throw ex;
}
}
Gordugunuz gibi GetFileList'de yaptigimiza benzer bir is yapiyoruz yalniz bu sefer Method olarak;
reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
kullaniyoruz. Bu kod bize klasor adresini bildigimiz herhangi bir dosyayi istedigimiz klasore indirmemizi sagliyor. Tahmin ettiginiz gibi Download folder'da yazdigimiz 2 metodu yani GetFileList ve Download'u kullanacak.
public static void DownloadFolder(string sourceDirectory, string destinationDirectory, string host, string user, string password)
{
try
{
string[] files = GetFileList(sourceDirectory, host, user, password);
foreach (string file in files)
{
Download(file, sourceDirectory, destinationDirectory, host, user, password);
}
}
catch(Exception ex)
{
throw ex;
}
}
Umarim acik olmustur.