How to download ftp server folders and files in windows application c# - c#

In my application, I have a FTP server containing some folders and those folders contain number of files and some are empty folders. I need to download all the folders as well as files into my local folder. How can I download them to my local folder?
I used the code below and got an exception:
public void DownloadFtpDirectory(string url, NetworkCredential credentials, string localPath)
{
FtpWebRequest listRequest = (FtpWebRequest)WebRequest.Create(url);
listRequest.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
listRequest.Credentials = credentials;
List<string> lines = new List<string>();
using (FtpWebResponse listResponse = (FtpWebResponse)listRequest.GetResponse())
using (Stream listStream = listResponse.GetResponseStream())
using (StreamReader listReader = new StreamReader(listStream))
{
while (!listReader.EndOfStream)
{
lines.Add(listReader.ReadLine());
}
}
foreach (string line in lines)
{
string[] tokens =
line.Split(new[] { ' ' }, 9, StringSplitOptions.RemoveEmptyEntries);
string name = tokens[8];
string permissions = tokens[0];
string localFilePath = Path.Combine(localPath, name);
string fileUrl = url + name;
if (permissions[0] == 'c')
{
if (!Directory.Exists(localFilePath))
{
Directory.CreateDirectory(localFilePath);
}
DownloadFtpDirectory(fileUrl + "/", credentials, localFilePath);
}
else
{
FtpWebRequest downloadRequest = (FtpWebRequest)WebRequest.Create(fileUrl);
downloadRequest.Method = WebRequestMethods.Ftp.DownloadFile;
downloadRequest.Credentials = credentials;
using (FtpWebResponse downloadResponse = (FtpWebResponse)downloadRequest.GetResponse())
using (Stream sourceStream = downloadResponse.GetResponseStream())
using (Stream targetStream = File.Create(localFilePath))
{
byte[] buffer = new byte[10240];
int read;
while ((read = sourceStream.Read(buffer, 0, buffer.Length)) > 0)
{
targetStream.Write(buffer, 0, read);
}
}
}
}
}
Exception

Related

Download Latest File in a SharePoint Folder

My current code downloads a SharePoint file from an absolute URL of the file and writes to local.
I want to change it to use the folder URL instead and downloads file in the folder base on some filter.
Can it be done?
Below is my current code snippet:
string fullFilePath = DownloadSPFile("http://MySharePointSite.com/sites/Collection1/Folder1/File1.docx/");
public static string DownloadSPFile(string urlPath)
{
string serverTempdocPath = "";
try
{
var request = (HttpWebRequest)WebRequest.Create(urlPath);
var credentials = new NetworkCredential("username", "password", "domain");
request.Credentials = credentials;
request.Timeout = 20000;
request.AllowWriteStreamBuffering = false;
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
using (Stream stream = response.GetResponseStream())
{
serverTempdocPath = Path.Combine(AppConfig.EmailSaveFilePath + "_DOWNLOADED.eml");
using (FileStream fs = new FileStream(serverTempdocPath, FileMode.Create))
{
byte[] read = new byte[256];
int count = stream.Read(read, 0, read.Length);
while (count > 0)
{
fs.Write(read, 0, count);
count = stream.Read(read, 0, read.Length);
}
}
}
}
}
catch (Exception ex)
{
AppLogger.LogError(ex, "");
throw ex;
}
return serverTempDocPath;
}
If your sharepoint site enables sharepoint rest api, you can get the details very easy.
Get list of files
url: http://site url/_api/web/GetFolderByServerRelativeUrl('/Folder Name')/Files
method: GET
headers:
Authorization: "Bearer " + accessToken
accept: "application/json;odata=verbose" or "application/atom+xml"
and pass query for that
"?filter=$top=1&$orderby=Created desc"
More information
Has you try to format your urlPath ?
like:
string urlPath = "path/to/folder/";
string fileFilter = "Cat.png";
string finalPath= String.format("{0}{1}", urlPath, fileFilter);
(Or anything like this)
(Hope I understand your question and I was able to help you ^^)

C# send file to ftp with user and port

How can I send a file to an ftp with C# ?
The only informations I have are :
FTP IP address
FTP port
FTP user
I've try this :
public void SendFile(string filePath)
{
String user = "UserID";
String IPAddr = "XXX.XXX.XXX.XXX";
int port = 9999;
using (WebClient client = new WebClient())
{
client.Credentials = new NetworkCredential(user, null);
Uri address = new Uri("ftp://" + IPAddr);
byte[] rawResponse = client.UploadFile(address, "STOR", filePath);
string response = System.Text.Encoding.ASCII.GetString(rawResponse);
// check response
}
}
But it doesn't work and it doesn't use the port (Error "unable to connect").
You can specify port in the address if you use an FtpWebRequest this is what i use and it works with specific port.
internal class FTPManager
{
private const string FTPAddress = "ftp://www.example.com:9211/";
private const string Username = "Yummy";
private const string Password = "Nachos";
public byte[] DownloadFile(string relativePath)
{
var fileData = new byte[0];
try
{
// parse the path
relativePath = ParseRelativePath(relativePath);
using (var request = new WebClient())
{
request.Credentials = new NetworkCredential(Username, Password);
fileData = request.DownloadData(FTPAddress + relativePath);
}
}
catch { }
return fileData;
}
public bool DoesFileExist(string relativePath)
{
var fileExist = false;
var request = WebRequest.Create(FTPAddress + ParseRelativePath(relativePath));
request.Method = WebRequestMethods.Ftp.GetFileSize;
request.Credentials = new NetworkCredential(Username, Password);
try
{
using (var response = request.GetResponse())
{
fileExist = true;
}
}
catch { }
return fileExist;
}
// upload file and handle everything
public void UploadFile(string relativePath, byte[] fileBinary)
{
// parse the path
relativePath = ParseRelativePath(relativePath);
// create the folder before writing the file
CreateFolders(relativePath);
// delete the file
DeleteFile(relativePath);
// upload the file
SendFile(relativePath, fileBinary);
}
private void SendFile(string relativePath, byte[] fileBinary)
{
try
{
var request = (FtpWebRequest)WebRequest.Create(FTPAddress + relativePath);
request.Method = WebRequestMethods.Ftp.UploadFile;
request.Credentials = new NetworkCredential(Username, Password);
var stream = request.GetRequestStream();
var sourceStream = new MemoryStream(fileBinary);
var length = 1024;
var buffer = new byte[length];
var bytesRead = 0;
do
{
bytesRead = sourceStream.Read(buffer, 0, length);
stream.Write(buffer, 0, bytesRead);
} while (bytesRead != 0);
sourceStream.Close();
stream.Close();
}
catch
{
}
}
private void DeleteFile(string relativePath)
{
try
{
WebRequest ftpRequest = WebRequest.Create(FTPAddress + relativePath);
ftpRequest.Method = WebRequestMethods.Ftp.DeleteFile;
ftpRequest.Credentials = new NetworkCredential(Username, Password);
ftpRequest.GetResponse();
}
catch { }
}
// parse the relative path for strange slashes
private string ParseRelativePath(string relativePath)
{
// split to remove all slashes and duplicates
var split = relativePath.Split(new string[] { "\\", "/" }, StringSplitOptions.RemoveEmptyEntries);
// join the string back with valid slash
var result = String.Join("/", split);
return result;
}
// Check if the relative path need folders to be created
private void CreateFolders(string relativePath)
{
if (relativePath.IndexOf("/") > 0)
{
var folders = relativePath.Split(new[] { "/" }, StringSplitOptions.None).ToList();
var folderToCreate = FTPAddress.Substring(0, FTPAddress.Length - 1);
for (int i = 0; i < folders.Count - 1; i++)
{
folderToCreate += ("/" + folders[i]);
CreateFolder(folderToCreate);
}
}
}
// create a single folder on the FTP
private void CreateFolder(string folderPath)
{
try
{
WebRequest ftpRequest = WebRequest.Create(folderPath);
ftpRequest.Method = WebRequestMethods.Ftp.MakeDirectory;
ftpRequest.Credentials = new NetworkCredential(Username, Password);
ftpRequest.GetResponse();
}
catch { } // create folder will fail if it already exist
}
}
My problem was undefined port. To set the port, just do :
Uri address = new Uri($"ftp://{IPAddr}:{port}");
byte[] rawResponse = client.UploadFile(address, "STOR", filePath);

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.

Listing server folders and sub folders using C# FtpWebRequest

I am trying to get full list of files, directories and sub-directories on tree view using StreamReader. The problem is it took too long and throws *"Operation time out exception" and shows only one level.
Here is my code
public void getServerSubfolder(TreeNode tv, string parentNode) {
string ptNode;
List<string> files = new List<string> ();
try {
FtpWebRequest request = (FtpWebRequest) WebRequest.
Create(parentNode);
request.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
request.Credentials = new NetworkCredential(this.userName, this.Password);
request.UseBinary = true;
request.UsePassive = true;
request.Timeout = 10000;
request.ReadWriteTimeout = 10000;
request.KeepAlive = false;
FtpWebResponse response = (FtpWebResponse) request.GetResponse();
Stream responseStream = response.GetResponseStream();
StreamReader reader = new StreamReader(responseStream);
string fileList;
string[] fileName;
//MessageBox.Show(reader.ReadToEnd().ToString());
while (!reader.EndOfStream) {
fileList = reader.ReadLine();
fileName = fileList.Split(' ');
if (fileName[0] == "drwxr-xr-x") {
// if it is directory
TreeNode tnS = new TreeNode(fileName[fileName.Length - 1]);
tv.Nodes.Add(tnS);
ptNode = parentNode + "/" + fileName[fileName.Length - 1] + "/";
getServerSubfolder(tnS, ptNode);
} else files.Add(fileName[fileName.Length - 1]);
}
reader.Close();
response.Close();
} catch (Exception ex) {
MessageBox.Show("Sub--here " + ex.Message + "----" + ex.StackTrace);
}
}
You have to read (and cache) whole listing before recursing into subdirectories, otherwise the top-level request will timeout before you complete subdirectories listing.
You can keep using ReadLine, no need to use ReadToEnd and separate the lines yourself.
void ListFtpDirectory(
string url, string rootPath, NetworkCredential credentials, List<string> list)
{
FtpWebRequest listRequest = (FtpWebRequest)WebRequest.Create(url + rootPath);
listRequest.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
listRequest.Credentials = credentials;
List<string> lines = new List<string>();
using (FtpWebResponse listResponse = (FtpWebResponse)listRequest.GetResponse())
using (Stream listStream = listResponse.GetResponseStream())
using (StreamReader listReader = new StreamReader(listStream))
{
while (!listReader.EndOfStream)
{
lines.Add(listReader.ReadLine());
}
}
foreach (string line in lines)
{
string[] tokens =
line.Split(new[] { ' ' }, 9, StringSplitOptions.RemoveEmptyEntries);
string name = tokens[8];
string permissions = tokens[0];
string filePath = rootPath + name;
if (permissions[0] == 'd')
{
ListFtpDirectory(url, filePath + "/", credentials, list);
}
else
{
list.Add(filePath);
}
}
}
Use the function like:
List<string> list = new List<string>();
NetworkCredential credentials = new NetworkCredential("user", "mypassword");
string url = "ftp://ftp.example.com/";
ListFtpDirectory(url, "", credentials, list);
A disadvantage of the above approach is that it has to parse server-specific listing to retrieve information about files and folders. The code above expects a common *nix-style listing. But many servers use a different format.
The FtpWebRequest unfortunately does not support the MLSD command, which is the only portable way to retrieve directory listing with file attributes in FTP protocol.
If you want to avoid troubles with parsing the server-specific directory listing formats, use a 3rd party library that supports the MLSD command and/or parsing various LIST listing formats; and recursive downloads.
For example with WinSCP .NET assembly you can list whole directory with a single call to the Session.EnumerateRemoteFiles:
// Setup session options
SessionOptions sessionOptions = new SessionOptions
{
Protocol = Protocol.Ftp,
HostName = "ftp.example.com",
UserName = "user",
Password = "mypassword",
};
using (Session session = new Session())
{
// Connect
session.Open(sessionOptions);
// List files
IEnumerable<string> list =
session.EnumerateRemoteFiles("/", null, EnumerationOptions.AllDirectories).
Select(fileInfo => fileInfo.FullName);
}
Internally, WinSCP uses the MLSD command, if supported by the server. If not, it uses the LIST command and supports dozens of different listing formats.
(I'm the author of WinSCP)
I'm doing similar things, but instead of using StreamReader.ReadLine() for each one, I get it all at once with StreamReader.ReadToEnd(). You don't need ReadLine() to just get a list of directories. Below is my entire code (Entire howto is explained in this tutorial):
FtpWebRequest request=(FtpWebRequest)FtpWebRequest.Create(path);
request.Method=WebRequestMethods.Ftp.ListDirectoryDetails;
List<ftpinfo> files=new List<ftpinfo>();
//request.Proxy = System.Net.WebProxy.GetDefaultProxy();
//request.Proxy.Credentials = CredentialCache.DefaultNetworkCredentials;
request.Credentials = new NetworkCredential(_username, _password);
Stream rs=(Stream)request.GetResponse().GetResponseStream();
OnStatusChange("CONNECTED: " + path, 0, 0);
StreamReader sr = new StreamReader(rs);
string strList = sr.ReadToEnd();
string[] lines=null;
if (strList.Contains("\r\n"))
{
lines=strList.Split(new string[] {"\r\n"},StringSplitOptions.None);
}
else if (strList.Contains("\n"))
{
lines=strList.Split(new string[] {"\n"},StringSplitOptions.None);
}
//now decode this string array
if (lines==null || lines.Length == 0)
return null;
foreach(string line in lines)
{
if (line.Length==0)
continue;
//parse line
Match m= GetMatchingRegex(line);
if (m==null) {
//failed
throw new ApplicationException("Unable to parse line: " + line);
}
ftpinfo item=new ftpinfo();
item.filename = m.Groups["name"].Value.Trim('\r');
item.path = path;
item.size = Convert.ToInt64(m.Groups["size"].Value);
item.permission = m.Groups["permission"].Value;
string _dir = m.Groups["dir"].Value;
if(_dir.Length>0 && _dir != "-")
{
item.fileType = directoryEntryTypes.directory;
}
else
{
item.fileType = directoryEntryTypes.file;
}
try
{
item.fileDateTime = DateTime.Parse(m.Groups["timestamp"].Value);
}
catch
{
item.fileDateTime = DateTime.MinValue; //null;
}
files.Add(item);
}
return files;

List all files from online FTP directory to a listview C#

How could i and everyone else who is reading this list all files from online directory to a listview?
This is the code for a local directory to be listed i would like to know if there was a way to make it so that is connects to a FTP website and lists files?
FolderBrowserDialog folderPicker = new FolderBrowserDialog();
if (folderPicker.ShowDialog() == DialogResult.OK)
{
ListView1.Items.Clear();
string[] files = Directory.GetFiles(folderPicker.SelectedPath);
foreach (string file in files)
{
string fileName = Path.GetFileNameWithoutExtension(file);
ListViewItem item = new ListViewItem(fileName);
item.Tag = file;
ListView1.Items.Add(item);
}
}
I have used this code but i cannot seem to get it to work its not coming up with an error but its not listing the files on the webserver either?
private void ConnectBtn_Click(object sender, EventArgs e)
{
ListDirectory();
}
public string[] ListDirectory()
{
var list = new List<string>();
var request = createRequest(TxtServer.Text, WebRequestMethods.Ftp.ListDirectory);
using (var response = (FtpWebResponse)request.GetResponse())
{
using (var stream = response.GetResponseStream())
{
using (var reader = new StreamReader(stream, true))
{
while (!reader.EndOfStream)
{
list.Add(reader.ReadLine());
}
}
}
}
return list.ToArray();
}
private FtpWebRequest createRequest(string uri, string method)
{
var r = (FtpWebRequest)WebRequest.Create(uri);
r.Credentials = new NetworkCredential(TxtUsername.Text, TxtPassword.Text);
r.Method = method;
return r;
}
You can use this wrapper library.
The relevant code is:
public string[] ListDirectory() {
var list = new List<string>();
var request = createRequest(WebRequestMethods.Ftp.ListDirectory);
using (var response = (FtpWebResponse)request.GetResponse()) {
using (var stream = response.GetResponseStream()) {
using (var reader = new StreamReader(stream, true)) {
while (!reader.EndOfStream) {
list.Add(reader.ReadLine());
}
}
}
}
return list.ToArray();
}
Here is a nice helper to get all files and folders of an FTP directory:
public static IEnumerable<string> GetFilesInFtpDirectory(string url, string username, string password)
{
// Get the object used to communicate with the server.
var request = (FtpWebRequest)WebRequest.Create(url);
request.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
request.Credentials = new NetworkCredential(username,password);
using (var response = (FtpWebResponse) request.GetResponse())
{
using (var responseStream = response.GetResponseStream())
{
var reader = new StreamReader(responseStream);
while (!reader.EndOfStream)
{
var line = reader.ReadLine();
if (string.IsNullOrWhiteSpace(line) == false)
{
yield return line.Split(new[] { ' ', '\t' }).Last();
}
}
}
}
}
Found here: http://www.snippetsource.net/Snippet/128/get-all-files-of-an-ftp-directory-in-c
I found the answer i did a little of experimenting and now its displaying the files in the listview, Thank you Robert Harvey♦
private void ConnectBtn_Click(object sender, EventArgs e)
{
ListDirectory();
}
public string[] ListDirectory()
{
var list = listView1;
var request = createRequest(TxtServer.Text, WebRequestMethods.Ftp.ListDirectory);
using (var response = (FtpWebResponse)request.GetResponse())
{
using (var stream = response.GetResponseStream())
{
using (var reader = new StreamReader(stream, true))
{
while (!reader.EndOfStream)
{
list.Items.Add(reader.ReadLine());
}
}
}
} List<string> l = new List<string>();
return l.ToArray();
}
private FtpWebRequest createRequest(string uri, string method)
{
var r = (FtpWebRequest)WebRequest.Create(uri);
r.Credentials = new NetworkCredential(TxtUsername.Text, TxtPassword.Text);
r.Method = method;
return r;
}
This code can be used to get the list of files from the ftp
private void ftpFileRead()
{
FtpWebRequest Request = (FtpWebRequest)WebRequest.Create("your ftpAddress");
Request.Method = WebRequestMethods.Ftp.ListDirectory;
Request.Credentials = new NetworkCredential(your ftp username,your ftp password);
FtpWebResponse Response = (FtpWebResponse)Request.GetResponse();
Stream ResponseStream = Response.GetResponseStream();
StreamReader Reader = new StreamReader(ResponseStream);
ListBox1.Items.Add(Response.WelcomeMessage);
while (!Reader.EndOfStream)//Read file name
{
ListBox1.Items.Add(Reader.ReadLine().ToString());
}
Response.Close();
ResponseStream.Close();
Reader.Close();
}
You can use this method.
public static string[] GetFiles(string path, NetworkCredential Credentials, SearchOption searchOption)
{
var request = (FtpWebRequest)WebRequest.Create(path);
request.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
request.Credentials = Credentials;
List<string> files = new List<string>();
using (var response = (FtpWebResponse)request.GetResponse())
{
using (var responseStream = response.GetResponseStream())
{
var reader = new System.IO.StreamReader(responseStream);
while (!reader.EndOfStream)
{
var line = reader.ReadLine();
if (string.IsNullOrWhiteSpace(line) == false)
{
if (!line.Contains("<DIR>"))
{
string[] details = line.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries);
string file = line.Replace(details[0], "")
.Replace(details[1], "")
.Replace(details[2], "")
.Trim();
files.Add(file);
}
else
{
if (searchOption == SearchOption.AllDirectories)
{
string dirName = line.Split(
new string[] { "<DIR>" },
StringSplitOptions.RemoveEmptyEntries
).Last().Trim();
string dirFullName = String.Format("{0}/{1}", path.Trim('/'), dirName);
files.AddRange(GetFiles(dirFullName, Credentials, searchOption));
}
}
}
}
}
}
return files.ToArray();
}

Categories