This question already has an answer here:
C# Download all files and subdirectories through FTP
(1 answer)
Closed 5 years ago.
I want to fetch the files from folder through FTP using c#, I have folder name called MyFolder, inside of this folder i have multiple folder, i need to fetch each file from all this folders which is inside the my MyFolder.Below code which i am getting all directories,Now i need to get each file.
Eg:httpdocs/Myfolder/newfolder/newfile.txt
/newfile1.txt
/newfile2.txt
httpdocs/Myfolder/newfolder1/newfile.txt
httpdocs/Myfolder/newfolder2/newfile.txt
FtpWebRequest ftpRequest =(FtpWebRequest)WebRequest.Create("ftp://www.xxxxxxx.com/httpdocs/MyFolder");
ftpRequest.Credentials = new NetworkCredential("xxxxx", "xxxxxx");
ftpRequest.Method = WebRequestMethods.Ftp.ListDirectory;
FtpWebResponse response = (FtpWebResponse)ftpRequest.GetResponse();
StreamReader streamReader = new StreamReader(response.GetResponseStream());
List<string> directories = new List<string>();
string line = streamReader.ReadLine();
while (!string.IsNullOrEmpty(line))
{
directories.Add(line);
line = streamReader.ReadLine();
}
streamReader.Close();
}
Have you had a look at the MSDN Documentation?
https://msdn.microsoft.com/de-de/library/ms229711(v=vs.110).aspx
public static void Main ()
{
// Get the object used to communicate with the server.
FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://www.contoso.com/test.htm");
request.Method = WebRequestMethods.Ftp.DownloadFile;
// This example assumes the FTP site uses anonymous logon.
request.Credentials = new NetworkCredential ("anonymous","janeDoe#contoso.com");
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
Stream responseStream = response.GetResponseStream();
StreamReader reader = new StreamReader(responseStream);
Console.WriteLine(reader.ReadToEnd());
Console.WriteLine("Download Complete, status {0}", response.StatusDescription);
reader.Close();
response.Close();
}
Edit: Already on StackOverflow Have a look here.
Related
I want to write a C# that:
Access the FTP with username and password
Goes to a certain folder
Sees what files aren't there from my PC folder and upload them.
My idea:
I have a folder called "mods" in my PC and another folder called "mods" in the FTP, so instead of opening the "FileZilla" software I want to write a C# that connects to the FTP and check what files aren't there.
Thank you so much!
you can list your file inftp server like this and do a comparaiosn with list file of mod dir
FtpWebRequest ftpRequest = (FtpWebRequest)WebRequest.Create(uri);
ftpRequest.Credentials =new NetworkCredential("anonymous","janeDoe#contoso.com");
ftpRequest.Method = WebRequestMethods.Ftp.ListDirectory;
FtpWebResponse response = (FtpWebResponse)ftpRequest.GetResponse();
StreamReader streamReader = new StreamReader(response.GetResponseStream());
List<string> directories = new List<string>();
string line = streamReader.ReadLine();
while (!string.IsNullOrEmpty(line))
{
directories.Add(line);
line = streamReader.ReadLine();
}
streamReader.Close();
There's no magic way, with a pure .NET framework (its FtpWebRequest class). You have to code it.
List the FTP folder
List the local folder
Find the missing files
Upload them one by one
void SynchronizeLocalAndFtpDirectory(
string localPath, string remoteUri, NetworkCredential credentials)
{
List<string> remoteFiles = new List<string>();
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(remoteUri);
request.Credentials = credentials;
request.Method = WebRequestMethods.Ftp.ListDirectory;
using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
while (!reader.EndOfStream)
{
remoteFiles.Add(reader.ReadLine());
}
}
IEnumerable<string> localFiles =
Directory.GetFiles(localPath).Select(path => Path.GetFileName(path));
IEnumerable<string> missingFiles = localFiles.Except(remoteFiles);
foreach (string filename in missingFiles)
{
Console.WriteLine("Uploading missing file {0}", filename);
string remoteFileUri = remoteUri + filename;
string localFilePath = Path.Combine(localPath, filename);
FtpWebRequest uploadRequest = (FtpWebRequest)WebRequest.Create(remoteFileUri);
uploadRequest.Method = WebRequestMethods.Ftp.UploadFile;
uploadRequest.Credentials = credentials;
using (Stream targetStream = uploadRequest.GetRequestStream())
using (Stream sourceStream = File.OpenRead(localFilePath))
{
byte[] buffer = new byte[10240];
int read;
while ((read = sourceStream.Read(buffer, 0, buffer.Length)) > 0)
{
targetStream.Write(buffer, 0, read);
}
}
}
}
Use the function like:
SynchronizeLocalAndFtpDirectory(
#"C:\local\mods", "ftp://ftp.example.com/remote/mods/",
new NetworkCredential("username", "password"));
(Do not forget the trailing slash in the URI).
Or use 3rd party FTP library that supports synchronization.
For example with the WinSCP .NET assembly, this is as easy as a single call to Session.SynchronizeDirectories.
And it will not only upload missing file, but also update out-of-the-date files and optionally delete orphan files.
void SynchronizeLocalAndFtpDirectory(
string localPath, string remotePath, SessionOptions sessionOptions)
{
using (Session session = new Session())
{
session.Open(sessionOptions);
session.SynchronizeDirectories(
SynchronizationMode.Remote, localPath, remotePath, false).Check();
}
}
Use it like:
SessionOptions sessionOptions = new SessionOptions()
{
Protocol = Protocol.Ftp,
HostName = "ftp.example.com",
UserName = "username",
Password = "password",
};
SynchronizeLocalAndFtpDirectory(#"C:\local\mods", "/remote/mods", sessionOptions);
(I'm the author of WinSCP)
I am trying to create a directory on my FTP server. I had already created ContractorDoc directory on server and want to create new directory NewDirectory in it.
try
{
FtpWebRequest request = (FtpWebRequest)FtpWebRequest.Create("ftp://abc.xyz.com/ContractorDoc/NewDirectory");
// Step 2 - Configure the connection request
request.Credentials = new NetworkCredential("uname", "passsword");
request.UsePassive = true;
request.UseBinary = true;
request.KeepAlive = false;
request.Method = WebRequestMethods.Ftp.MakeDirectory;
// Step 3 - Call GetResponse() method to actually attempt to create the directory
FtpWebResponse makeDirectoryResponse = (FtpWebResponse)request.GetResponse();
}
catch (WebException ex)
{
String status = ((FtpWebResponse)ex.Response).StatusDescription;
}
I get an exception:
550 Cannot create a file when that file already exists.
Am I missing something?
I think he's got to make sure there folder.
There is no error in the code. Maybe there's a problem with the server.
FtpWebRequest ftpRequest = (FtpWebRequest)WebRequest.Create("ftp://abc.xyz.com/ContractorDoc");
ftpRequest.Credentials =new NetworkCredential("uname","password");
ftpRequest.Method = WebRequestMethods.Ftp.ListDirectory;
FtpWebResponse response = (FtpWebResponse)ftpRequest.GetResponse();
StreamReader streamReader = new StreamReader(response.GetResponseStream());
List<string> directories = new List<string>();
string line = streamReader.ReadLine();
while (!string.IsNullOrEmpty(line))
{
directories.Add(line);
line = streamReader.ReadLine();
}
streamReader.Close();
This method does work and does adding the files to the listBox.
But some of the files are directories and i wonder if there is a way to display the directories witha directory symbol this yellow directory near it ?
public void getFtpFileList()
{
List<string> files = new List<string>();
try
{
FtpWebRequest request = FtpWebRequest.Create("ftp://"+ txtHost.Text) as FtpWebRequest;
request.Method = WebRequestMethods.Ftp.ListDirectory;
request.Credentials = new NetworkCredential(txtUsername.Text, txtPassword.Text);
request.UsePassive = true;
request.UseBinary = true;
request.KeepAlive = false;
FtpWebResponse response = request.GetResponse() as FtpWebResponse;
Stream responseStream = response.GetResponseStream();
StreamReader reader = new StreamReader(responseStream);
while (!reader.EndOfStream)
{
files.Add(reader.ReadLine());
}
foreach (string file in files)
{
listBox1.Items.Add(file);
}
reader.Close();
responseStream.Close();
response.Close();
}
catch (Exception ex)
{
}
}
This is a screenshot on the top left is my program and under it it's my ftp.
I want somehow to display on the listBox as much as close the way it look like in my ftp server.
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!!
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.
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).
Is there any way to deal with situation when you need to get list of all directories on a FTP server, where the number of directories is so big that it takes too long to get it and operation fails with timeout?
I wonder if there are some libraries that let you do that somehow?
Try something like this
FtpWebRequest ftpRequest = (FtpWebRequest)WebRequest.Create(uri);
ftpRequest.Credentials = new NetworkCredential("anonymous","yourName#SomeDomain.com");//replace with your Creds
ftpRequest.Method = WebRequestMethods.Ftp.ListDirectory;
FtpWebResponse response = (FtpWebResponse)ftpRequest.GetResponse();
StreamReader streamReader = new StreamReader(response.GetResponseStream());
List<string> directories = new List<string>();
string line = streamReader.ReadLine();
while (!string.IsNullOrEmpty(line))
{
directories.Add(line);
line = streamReader.ReadLine();
}
streamReader.Close();
// also add some code that will Dispose of the StreamReader object
// something like ((IDisposable)streanReader).Dispose();
// Dispose of the List<string> as well
line = null;