Here is how I did it in my application. My application is in VB .NET so I converted it to C# for you using Developer Fusion's VB .NET to C# converter. This example builds a collection named
colFTPDirectory
that contains the names of all of the .TXT files in the FTP directory along with their creation date and size.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Net;
...
bool bOK = false;
FtpWebRequest request = null;
FtpWebResponse response = null;
Stream responseStream = null;
StreamReader reader = null;
string strFilename = null;
System.DateTime dtCreated = null;
int intSize = 0;
string strTemp = null;
System.Collections.Generic.List<ftpdirectoryinfo> colFTPDirectory = null;
try {
bOK = false;
LogIt("Retrieving directory listing from " + strServerName + "/" + strFolder);
request = (FtpWebRequest)WebRequest.Create("ftp://" + strServerName + "/" + strFolder);
request.Timeout = 60000;
request.ReadWriteTimeout = 60000;
request.Credentials = new NetworkCredential(strUsername, strPassword);
request.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
response = (FtpWebResponse)request.GetResponse();
LogIt(response.BannerMessage);
LogIt(response.WelcomeMessage);
responseStream = response.GetResponseStream();
reader = new StreamReader(responseStream);
colFTPDirectory = new System.Collections.Generic.List<FTPDirectoryInfo>();
while (!reader.EndOfStream) {
strTemp = Convert.ToString(reader.ReadLine());
dtCreated = Convert.ToDateTime(strTemp.Substring(0, 20).Trim);
intSize = Convert.ToInt32(strTemp.Substring(20, 18).Trim);
strFilename = strTemp.Substring(39).Trim;
if (Path.GetExtension(strFilename).ToLower == ".txt") {
colFTPDirectory.Add(new FTPDirectoryInfo(strFilename, dtCreated, intSize));
}
}
bOK = true;
} catch (Exception ex) {
LogIt("ERROR: " + ex.Message);
} finally {
try {
reader.Close();
} catch {
}
try {
response.Close();
} catch {
}
reader = null;
response = null;
}
...
internal class FTPDirectoryInfo
{
private string m_filename;
private System.DateTime m_CreationDate;
private int m_size;
public FTPDirectoryInfo(string Filename, System.DateTime CreationDate, int Size)
{
m_filename = Filename;
m_CreationDate = CreationDate;
m_size = Size;
}
public System.DateTime CreationDate {
get { return m_CreationDate; }
}
public string Filename {
get { return m_filename; }
}
public int Size {
get { return m_size; }
}
}