ftp subfolder downloading recursion function is not working - c#

I'm trying to download all files including sub folders from ftp in c#.
I created DownloadDiretory for recursion of the sub folders and DownloadFtpFile for downloading files.
The code works fine for the root folder file download, but it is not downloading any subfolder files.
Any suggestions?
Thanks in Advance.
public static void DownloadDiretory(string folderPath)
{
try
{
ConnectionsXml objXml = new ConnectionsXml();
AccountFtp account = objXml.GetAccountFtpDetails();
FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://" + account.Website + "/" + folderPath);
request.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
request.Credentials = new NetworkCredential(account.UserId, account.Password);
request.Timeout = 360000;
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
//FtpWebResponse response = GetFtpResponse(folderPath);
Stream responseStream = response.GetResponseStream();
StreamReader reader = new StreamReader(responseStream, true);
string filename;
while (!reader.EndOfStream)
{
filename = string.Empty;
filename = reader.ReadLine();
if (filename.Contains("<DIR>"))
{
filename = filename.Substring(filename.IndexOf("<DIR>", 0) + 5, filename.Length - (filename.IndexOf("<DIR>", 0) + 5));
filename = filename.Trim();
DownloadDiretory(folderPath + "/" + filename);
}
else
{
string[] files = filename.Split(' ');
filename = files[files.Length - 1];
DownloadFtpFile(folderPath, filename);
}
}
responseStream.Close();
response.Close();
}
catch (Exception Ex)
{
MessageBox.Show(Ex.Message);
}
}
public static void DownloadFtpFile(string folderName, string fileName)
{
try
{
ConnectionsXml objXml = new ConnectionsXml();
AccountFtp account = objXml.GetAccountFtpDetails();
string path = "ftp://" + account.Website + "/" + folderName + "/" + fileName;
FtpWebRequest request = (FtpWebRequest)WebRequest.CreateDefault(new Uri(path));
request.Method = WebRequestMethods.Ftp.DownloadFile;
request.Credentials = new NetworkCredential(account.UserId, account.Password);
//request.Timeout = 360000;
request.KeepAlive = false;
request.UsePassive = true;
request.UseBinary = true;
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
Stream responseStream = response.GetResponseStream();
if(!Directory.Exists(#"F:\MPR\" + folderName))
{
Directory.CreateDirectory(#"F:\MPR\" + folderName);
}
FileStream fileStream = new FileStream(#"F:\MPR\" + folderName + #"\" + fileName, FileMode.Create);
byte[] bytesbuffer = new byte[32 * 1024];
int byteRead = responseStream.Read(bytesbuffer, 0, 2048);
while (byteRead > 0)
{
fileStream.Write(bytesbuffer, 0, byteRead);
byteRead = responseStream.Read(bytesbuffer, 0, 2048);
}
responseStream.Close();
fileStream.Close();
response.Close();
}
catch (Exception Ex)
{
MessageBox.Show(Ex.Message);
}
}

Your condition filename.Contains("DIR")) seems to be wrong. I have no private ftp server available, so I tried on ftp://test.talia.net. The folder "incoming" gets returned as
"drwxrwxr-x 2 ftp ftp 4096 Oct 15 07:32 incoming"
Files get returned as eg
"-rw-r--r-- 1 ftp ftp 10485760 Apr 19 2006 10mb.pak"
So try to check with filename.StartsWith("d").
Also, these lines:
filename = string.Empty;
filename = reader.ReadLine();
serve no real purpose. Better set filename to string.Empty before entering the loop.

Related

Uploading files to FTP server works on localhost, but not when deployed

I've been spending all day trying to figure this one out, but with no luck.
Basically I have a bunch of files and folders, that I want to upload to a FTP server, and everything works great on localhost. But when I deploy it to azure, it stops working. In my head it makes no sense, and my initial thought was it had to do with a firewall, upload timeout or something else.
Do you see anything I am missing in my code, or do I need to do some configuration on azure or my ftp server ?
Edit: I forgot to include the error message:
"The underlying connection was closed: An unexpected error occurred on a receive
Problem Id:System.Net.WebException at simplecms.Models.FtpConn.UploadFile"
public class FtpConn
{
public string UploadCms(string address, string username, string password, string host, bool userftp, string guid)
{
CreateFileUID(guid);
string location;
if (userftp)
{
location = address + "/simplecms/";
host = host + "/simplecms/";
}
else
{
location = address + "/simplecms" + guid + "/";
host = host + "/simplecms" + guid + "/";
}
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(location);
request.Credentials = new NetworkCredential(username, password);
//request.Timeout = -1;
request.UsePassive = true;
request.UseBinary = true;
request.Timeout = 1000000000;
request.KeepAlive = false;
request.ReadWriteTimeout = 1000000000;
request.Method = WebRequestMethods.Ftp.MakeDirectory;
using (var resp = (FtpWebResponse)request.GetResponse())
{
Console.WriteLine(resp.StatusCode);
}
string cmsFolder = "wwwroot/dist/";
string[] cmsFiles = Directory.GetFiles(cmsFolder);
foreach (string file in cmsFiles)
{
string path = Path.GetFullPath(file);
string name = Path.GetFileName(file);
UploadFile(username, password, location, path, name);
}
string[] staticFiles = Directory.GetDirectories(cmsFolder);
string[] subs = Directory.GetDirectories(cmsFolder + "static/");
foreach (string file in staticFiles)
{
CreateDirectory(username, password, location + "/" + Path.GetFileName(file));
}
foreach (string folder in subs)
{
CreateDirectory(username, password, location + "/static/" + Path.GetFileName(folder));
foreach (string subfile in Directory.GetFiles(folder))
{
string path = Path.GetFullPath(subfile);
string name = Path.GetFileName(subfile);
UploadFile(username, password, location + "/static/" + Path.GetFileName(folder) + "/" + Path.GetFileName(subfile), path, "");
}
}
return host;
}
private void UploadFile(string username, string password, string location, string filePath, string fileName)
{
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(location + fileName);
request.Credentials = new NetworkCredential(username, password);
//request.Timeout = -1;
request.UsePassive = true;
request.UseBinary = true;
request.Timeout = 1000000000;
request.KeepAlive = false;
request.ReadWriteTimeout = 1000000000;
request.Method = WebRequestMethods.Ftp.UploadFile;
FileStream stream = File.OpenRead(filePath);
byte[] buffer = new byte[stream.Length];
stream.Read(buffer, 0, buffer.Length);
stream.Close();
Stream reqStream = request.GetRequestStream();
reqStream.Write(buffer, 0, buffer.Length);
reqStream.Close();
}
private void CreateDirectory(string username, string password, string newDirectory)
{
try
{
FtpWebRequest ftpRequest = (FtpWebRequest)WebRequest.Create(newDirectory);
ftpRequest.Credentials = new NetworkCredential(username, password);
//ftpRequest.Timeout = -1;
ftpRequest.UseBinary = true;
ftpRequest.UsePassive = true;
ftpRequest.KeepAlive = false;
ftpRequest.Method = WebRequestMethods.Ftp.MakeDirectory;
FtpWebResponse ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();
ftpResponse.Close();
ftpRequest = null;
}
catch (Exception ex) { Console.WriteLine(ex); }
return;
}
private void CreateFileUID(string uid)
{
string folderName = "wwwroot/dist/";
string[] txtList = Directory.GetFiles(folderName, "*.txt");
foreach (string f in txtList)
{
File.Delete(f);
}
string fileName = "uid.txt";
string pathString = Path.Combine(folderName, fileName);
using (FileStream fs = File.Create(pathString))
{
byte[] SimpleCmsUID = new UTF8Encoding(true).GetBytes(uid);
fs.Write(SimpleCmsUID, 0, SimpleCmsUID.Length);
}
}
}

How to download files from ftp from particular folder

I create a windows form to download files from ftp from particular folder.
The user put the ftp details with username and password and folder name from which file will be download all the files. This will set by user one time and the all file from ftp describe folder will download everyday.
Example on FTP Folder Name is MyFolder where a.docx, b.docx etc it will download a.docx, b.docx everyday not other folder data need to download.
For download and list of file I use below function. Can you please tell me what I am doing mistake or how can I do this .
private void downloadFileFromFTP()
{
try
{
string[] files = GetFileList();
foreach (string file in files)
{
Download(file);
}
}
catch (Exception ex)
{
}
}
For Get The List of 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://" + txtftpAddress.Text + "/")); //txtFtpAddress.Text + "/" + txtFTPFolderName + "/" + file
reqFTP.UseBinary = true;
reqFTP.Credentials = new NetworkCredential("UserNm", "passwd");
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;
}
}
download the file form the folder
private void Download(string file)
{
try
{
string uri = "ftp://" + txtFtpAddress.Text.Trim() + "/" + "txtlodername.Text" + "/" + file;
Uri serverUri = new Uri(uri);
if (serverUri.Scheme != Uri.UriSchemeFtp)
{
return;
}
FtpWebRequest reqFTP;
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(txtFtpAddress.Text + "/" + txtFTPFolderName + "/" + file));
reqFTP.Credentials = new NetworkCredential("UserName", "mypass");
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();
FileStream writeStream = new FileStream("D\\Temp" + 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)
{
MessageBox.Show(wEx.Message, "Download Error");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Download Error");
}
}
I think 3 lines of your Download method have to be corrected as follows:
1.
string uri = "ftp://" + txtFtpAddress.Text.Trim() + "/" + "txtlodername.Text" + "/" + file;
should be:
string uri = "ftp://" + txtFtpAddress.Text.Trim() + "/" + txtFTPFolderName.Text.Trim() + "/" + file;
2.
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(txtFtpAddress.Text + "/" + txtFTPFolderName + "/" + file));
should be:
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
3.
FileStream writeStream = new FileStream("D\\Temp" + file, FileMode.Create);
should be:
FileStream writeStream = new FileStream("D:\\Temp\\" + file, FileMode.Create);

How to Download file from one FTP and then Upload file to different FTP?

I am trying to download a file from one FTP server, and then upload it to a different FTP. I only figured out how to upload local files and download XML via FTP so far.
Here is my method to upload local file to FTP:
private void UploadLocalFile(string sourceFileLocation, string targetFileName)
{
try
{
string ftpServerIP = "ftp://testing.com/ContentManagementSystem/"+ Company +"/Prod";
string ftpUserID = Username;
string ftpPassword = Password;
string filename = "ftp://" + ftpServerIP + "/" + targetFileName;
FtpWebRequest ftpReq = (FtpWebRequest)WebRequest.Create(filename);
ftpReq.UseBinary = true;
ftpReq.Method = WebRequestMethods.Ftp.UploadFile;
ftpReq.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
ftpReq.Proxy = null;
byte[] b = File.ReadAllBytes(sourceFileLocation);
ftpReq.ContentLength = b.Length;
using (Stream s = ftpReq.GetRequestStream())
{
s.Write(b, 0, b.Length);
}
}
catch (WebException ex)
{
String status = ((FtpWebResponse)ex.Response).StatusDescription;
Console.WriteLine(status);
}
}
And here is my method for downloading XML from FTP:
private static XmlDocument DownloadFtpXml(string uri, int retryLimit)
{
var returnDocument = new XmlDocument();
try
{
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(uri);
request.Method = WebRequestMethods.Ftp.DownloadFile;
request.Credentials = new NetworkCredential(Username, Password);
request.UsePassive = true;
request.Proxy = new WebProxy();
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
using (Stream responseStream = response.GetResponseStream())
{
returnDocument.Load(responseStream);
}
}
catch (WebException ex)
{
if (ex.Response != null)
{
FtpWebResponse response = (FtpWebResponse)ex.Response;
if (response.StatusCode == FtpStatusCode.ActionNotTakenFileUnavailable)
{
}
}
}
return returnDocument;
}
I'm unsure exactly how to do it, but I'm trying to create a method that will download something (content will be a video or image) from one FTP and then turn around and upload what I've just downloaded (that I'll have held in memory) to a different FTP.
Please help!
You were so close! Use a stream to convert your download into a byte array for upload.
I recently made a program to do just this! This will currently copy all files from one FTP directory to another so long as there is not a file in the target directory with the same name. It would be easy to change if you only wanted to copy one file, just use the copyFile, toByteArray and upload functions:
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
namespace Copy_From_FTP
{
class Program
{
public static void Main(string[] args)
{
List<FileName> sourceFileList = new List<FileName>();
List<FileName> targetFileList = new List<FileName>();
//string targetURI = ftp://www.target.com
//string targetUser = userName
//string targetPass = passWord
//string sourceURI = ftp://www.source.com
//string sourceUser = userName
//string sourcePass = passWord
getFileLists(sourceURI, sourceUser, sourcePass, sourceFileList, targetURI, targetUser, targetPass, targetFileList);
Console.WriteLine(sourceFileList.Count + " files found!");
CheckLists(sourceFileList, targetFileList);
targetFileList.Sort();
Console.WriteLine(sourceFileList.Count + " unique files on sourceURI"+Environment.NewLine+"Attempting to move them.");
foreach(var file in sourceFileList)
{
try
{
CopyFile(file.fName, sourceURI, sourceUser, sourcePass, targetURI, targetUser, targetPass);
}
catch
{
Console.WriteLine("There was move error with : "+file.fName);
}
}
}
public class FileName : IComparable<FileName>
{
public string fName { get; set; }
public int CompareTo(FileName other)
{
return fName.CompareTo(other.fName);
}
}
public static void CheckLists(List<FileName> sourceFileList, List<FileName> targetFileList)
{
for (int i = 0; i < sourceFileList.Count;i++ )
{
if (targetFileList.BinarySearch(sourceFileList[i]) > 0)
{
sourceFileList.RemoveAt(i);
i--;
}
}
}
public static void getFileLists(string sourceURI, string sourceUser, string sourcePass, List<FileName> sourceFileList,string targetURI, string targetUser, string targetPass, List<FileName> targetFileList)
{
string line = "";
/////////Source FileList
FtpWebRequest sourceRequest;
sourceRequest = (FtpWebRequest)WebRequest.Create(sourceURI);
sourceRequest.Credentials = new NetworkCredential(sourceUser, sourcePass);
sourceRequest.Method = WebRequestMethods.Ftp.ListDirectory;
sourceRequest.UseBinary = true;
sourceRequest.KeepAlive = false;
sourceRequest.Timeout = -1;
sourceRequest.UsePassive = true;
FtpWebResponse sourceRespone = (FtpWebResponse)sourceRequest.GetResponse();
//Creates a list(fileList) of the file names
using (Stream responseStream = sourceRespone.GetResponseStream())
{
using (StreamReader reader = new StreamReader(responseStream))
{
line = reader.ReadLine();
while (line != null)
{
var fileName = new FileName
{
fName = line
};
sourceFileList.Add(fileName);
line = reader.ReadLine();
}
}
}
/////////////Target FileList
FtpWebRequest targetRequest;
targetRequest = (FtpWebRequest)WebRequest.Create(targetURI);
targetRequest.Credentials = new NetworkCredential(targetUser, targetPass);
targetRequest.Method = WebRequestMethods.Ftp.ListDirectory;
targetRequest.UseBinary = true;
targetRequest.KeepAlive = false;
targetRequest.Timeout = -1;
targetRequest.UsePassive = true;
FtpWebResponse targetResponse = (FtpWebResponse)targetRequest.GetResponse();
//Creates a list(fileList) of the file names
using (Stream responseStream = targetResponse.GetResponseStream())
{
using (StreamReader reader = new StreamReader(responseStream))
{
line = reader.ReadLine();
while (line != null)
{
var fileName = new FileName
{
fName = line
};
targetFileList.Add(fileName);
line = reader.ReadLine();
}
}
}
}
public static void CopyFile(string fileName, string sourceURI, string sourceUser, string sourcePass,string targetURI, string targetUser, string targetPass )
{
try
{
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(sourceURI + fileName);
request.Method = WebRequestMethods.Ftp.DownloadFile;
request.Credentials = new NetworkCredential(sourceUser, sourcePass);
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
Stream responseStream = response.GetResponseStream();
Upload(fileName, ToByteArray(responseStream),targetURI,targetUser, targetPass);
responseStream.Close();
}
catch
{
Console.WriteLine("There was an error with :" + fileName);
}
}
public static Byte[] ToByteArray(Stream stream)
{
MemoryStream ms = new MemoryStream();
byte[] chunk = new byte[4096];
int bytesRead;
while ((bytesRead = stream.Read(chunk, 0, chunk.Length)) > 0)
{
ms.Write(chunk, 0, bytesRead);
}
return ms.ToArray();
}
public static bool Upload(string FileName, byte[] Image, string targetURI,string targetUser, string targetPass)
{
try
{
FtpWebRequest clsRequest = (FtpWebRequest)WebRequest.Create(targetURI+FileName);
clsRequest.Credentials = new NetworkCredential(targetUser, targetPass);
clsRequest.Method = WebRequestMethods.Ftp.UploadFile;
Stream clsStream = clsRequest.GetRequestStream();
clsStream.Write(Image, 0, Image.Length);
clsStream.Close();
clsStream.Dispose();
return true;
}
catch
{
return false;
}
}
}
}
You may run into issues if you are using things that have special encoding, like text documents. That can be changed by the way the upload function is used. If you're doing text files, use:
System.Text.Encoding.UTF8.GetBytes(responseStream)
instead of
ToByteArray(responseStream)
You could do a simple extension check of your file before executing the upload.

Error while uploading a text file to FTP server C#

I am building a simple application that uploads a .txt file to a FTP server. I have done this before and i am using the same code as i used for the other application.
this is my code:
string localFilePath = #"\\fileprint\data\Groups\Operation\fileExports\dls\";
string archiveFilePath = #"\\fileprint\data\Groups\Operation\fileExports\dls\Archive\";
string logFilePath = #"C:\Users\lmy\Desktop\Logs";
string ftpServer = "ftp://server:21/home/out2233/tmp";
private string logFileName = "" + DateTime.Now.Year.ToString() + "-" + DateTime.Now.Month.ToString() + "-" + DateTime.Now.Day.ToString();
public void UploadFile()
{
try
{
string[] files = Directory.GetFiles(localFilePath);
foreach (string file in files)
{
string fileName = Path.GetFileName(file);
string modified = file.Remove(60, 6);
string modifiedFile = Path.GetFileName(modified);
FtpWebRequest ftpReq = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpServer + modifiedFile));
ftpReq.Method = WebRequestMethods.Ftp.UploadFile;
ftpReq.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
ftpReq.UsePassive = true;
ftpReq.UseBinary = true;
ftpReq.KeepAlive = true;
ftpReq.Credentials = new NetworkCredential("out2233", "password");
ftpReq.EnableSsl = true;
FileInfo fileInfo = new FileInfo(localFilePath + #"\" + fileName);
FileStream fileStream = fileInfo.OpenRead();
byte[] fileContent = new byte[fileInfo.Length];
fileStream.Read(fileContent, 0, Convert.ToInt32(fileInfo.Length));
Stream writer = ftpReq.GetRequestStream();
writer.Write(fileContent, 0, fileContent.Length);
fileStream.Close();
writer.Close();
FtpWebResponse response = (FtpWebResponse)ftpReq.GetResponse();
AppendLogFile(response, "Uploaded Files: ", fileName);
MoveToArchive(file, archiveFilePath + fileName);
}
}
catch (Exception exception)
{
Console.WriteLine(exception.Message);
}
}
But it get this error:
exception = {"Cannot send a content-body with this verb-type."}
when the code reaches this line:
Stream writer = ftpReq.GetRequestStream();
I have googled this but i can only find ASP examples. I cant seem to find out what i am doing wrong here. Hope you guys can help me.
thanks!
Looks like, you're trying to list ftp directory content, with this line:
ftpReq.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
(http://msdn.microsoft.com/en-us/library/system.net.webrequestmethods.ftp.listdirectorydetails%28v=vs.110%29.aspx)
Try removing it, leaving only this line:
ftpReq.Method = WebRequestMethods.Ftp.UploadFile;
http://msdn.microsoft.com/en-us/library/system.net.webrequestmethods.ftp.uploadfile%28v=vs.110%29.aspx

File Download from Ftp server with case insencitive match c#

Here is my code to download file from ftp server but it's case sensitive match.. could you please help me to download with out case match.
ex: if i'm trying to download "6Gt6hh.xml" but existing file in ftp sever is "6GT6hh.Xml". its not download with my code could you please help me.
private void Download(string file, ServerCredentials FtpCdrl, string DayOfYear, string dest, string ab)
{
try
{
string uri = "ftp://" + FtpCdrl.Host + "/" + FtpCdrl.DirPath.Replace("\\", "/") + "/" + DayOfYear + "/" + file;
Uri serverUri = new Uri(uri);
if (serverUri.Scheme != Uri.UriSchemeFtp)
{
return;
}
if (!Directory.Exists(dest))
Directory.CreateDirectory(dest);
if (!Directory.Exists(dest + "\\" + ab))
Directory.CreateDirectory(dest + "\\" + ab);
FtpWebRequest reqFTP;
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + FtpCdrl.Host + "/" + FtpCdrl.DirPath.Replace("\\", "/") + "/" + DayOfYear + "/" + file));
reqFTP.Credentials = new NetworkCredential(FtpCdrl.UID, FtpCdrl.Pwd);
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();
FileStream writeStream = new FileStream(dest + "\\" + ab + "\\" + 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);
}
status("File Downloaded Successfully: .\\" + ab + "\\" + file, Color.Green);
writeStream.Close();
response.Close();
failed = 0;
}
catch (WebException wEx)
{
failed++;
status("[Download Error]" + wEx.Message, Color.Red);
if (failed < 3)
Download(file, FtpCdrl, DayOfYear, dest, ab);
}
catch (Exception ex)
{
status("[Download Error]" + ex.Message, Color.Red);
}
}
public class ServerCredentials
{
public string Host, UID, Pwd, DirPath;
public int Pst;
public string Mail;
public string facility;
public string Batchextn;
public ServerCredentials(string _Host1, string _DirPath1, string _Uid1, string _Pwd1, string _Mail, int _Pst1, string _facility, string _batchextn)
{
Host = _Host1;
UID = _Uid1;
Pwd = _Pwd1;
DirPath = _DirPath1;
Pst = _Pst1;
Mail = _Mail;
facility = _facility;
Batchextn = _batchextn;
}
}
public List<ServerCredentials> Svr = new List<ServerCredentials>();
Uris are case sensetive and it is up to server to allow case insensetive acces to files. I.e. traditionally most HTTP servers ignore case in the path portion of Uri, but often respect case in Query portion.
In your case it looks like the FTP server you access enforces case match for file names (common for Unix/Linux servers) and may even have multiple files with different casing.
The correct implementation would be to list content first and than pick the file name from the list of files. The how to: List Directory Contents with FTP article covers this step.
FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://www.contoso.com/");
request.Credentials = new NetworkCredential ("anonymous","janeDoe#contoso.com");
request.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
using(var response = (FtpWebResponse)request.GetResponse())
using(var responseStream = response.GetResponseStream())
using(var reader = new StreamReader(responseStream))
{
Console.WriteLine(reader.ReadToEnd());
}

Categories