public class FTPClient {
// The hostname or IP address of the FTP server
private string _remoteHost;
// The remote username
private string _remoteUser;
// Password for the remote user
private string _remotePass;
public FTPClient(string remoteHost, string remoteUser, string remotePassword) {
_remoteHost = remoteHost;
_remoteUser = remoteUser;
_remotePass = remotePassword;
}
public string DirectoryListing() {
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(_remoteHost);
request.Method = WebRequestMethods.Ftp.ListDirectory;
request
.Credentials = new NetworkCredential
(_remoteUser, _remotePass
); FtpWebResponse response = (FtpWebResponse)request.GetResponse();
Stream responseStream = response.GetResponseStream();
StreamReader reader
= new StreamReader
(responseStream
);
string result = string.Empty;
while (!reader.EndOfStream) {
result += reader.ReadLine() + Environment.NewLine;
}
reader.Close();
response.Close();
return result;
}
public string DirectoryListing(string folder) {
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(_remoteHost + folder);
request.Method = WebRequestMethods.Ftp.ListDirectory;
request
.Credentials = new NetworkCredential
(_remoteUser, _remotePass
); FtpWebResponse response = (FtpWebResponse)request.GetResponse();
Stream responseStream = response.GetResponseStream();
StreamReader reader
= new StreamReader
(responseStream
);
string result = string.Empty;
while (!reader.EndOfStream) {
result += reader.ReadLine() + Environment.NewLine;
}
reader.Close();
response.Close();
return result;
}
public void Download(string file, string destination) {
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(_remoteHost + file);
request.Method = WebRequestMethods.Ftp.DownloadFile;
request
.Credentials = new NetworkCredential
(_remoteUser, _remotePass
); FtpWebResponse response = (FtpWebResponse)request.GetResponse();
Stream responseStream = response.GetResponseStream();
StreamReader reader
= new StreamReader
(responseStream
);
StreamWriter writer
= new StreamWriter
(destination
); writer.Write(reader.ReadToEnd());
writer.Close();
reader.Close();
response.Close();
}
public void UploadFile(string FullPathFilename) {
string filename = Path.GetFileName(FullPathFilename);
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(_remoteHost + filename);
request.Method = WebRequestMethods.Ftp.UploadFile;
request
.Credentials = new NetworkCredential
(_remoteUser, _remotePass
);
StreamReader sourceStream
= new StreamReader
(FullPathFilename
); byte[] fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());
request.ContentLength = fileContents.Length;
Stream requestStream = request.GetRequestStream();
requestStream.Write(fileContents, 0, fileContents.Length);
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
response.Close();
requestStream.Close();
sourceStream.Close();
}
}