Last Updated:

FTP Class

The FTP class is designed to work with an FTP server

Class Constructor

public FTP (string Host, int Port, string User, string Password)

Creates an object and initializes the connection parameters to the FTP server

Options:

  • Host – name or IP address of the FTP server;
  • Port – port number of the FTP server;
  • User – account name;
  • Password – account password;

Class Methods

public bool UploadFile (string PathFTP, string NameFile)

Writes a NameFile to the FTP server at the specified PathFTP path.

Options:

  • PathFTP – path;
  • NameFile is the name of the file.

The returned result is:

  • Returns true if the file entry was successful, otherwise returns false.

Note:

  • The PathFTP path is specified without a destination slash.

public bool DownloadFile (string NameFileFTP, string NameFileLocal)

Downloads a NameFileFTP file from an FTP server and writes the downloaded file to a local computer named NameFileLocal.

Options:

  • NameFileFTP – file name on the FTP server;
  • NameFileLocal is the name of the file on the local computer.

The returned result is:

  • Returns true if the file was loaded successfully, otherwise returns false.

public string[] ListDirectory (string PathFTP, bool Details)

Generates a list of files and directories located in the specified PathFTP on the FTP server.

Options:

  • PathFTP – path to the directory on the FTP server;
  • Details – a form of data issuance. With Details = true, the full form of the data output is otherwise short. The full form of data issuance depends on the platform on which the FTP server is installed.

Windows Platform

06-04-10  09:25AM                 Book
06-15-06  10:27AM                 docs
02-20-07  03:13PM                 docum
12-30-10  10:40AM                 Instr
06-30-09  02:04PM                 Monitoring
01-31-11  11:20AM                28027 POOL.RET
03-05-10  01:58PM                 Program
01-31-11  09:44AM                 Tov
01-31-11  11:20AM                97960 user.net
11-24-10  02:00PM                 Forms
12-18-08 01:46PM 339248 CUMR.emf server schema

Unix Platform

dr-xr-xr-x   1 user     group           0 Feb  3 13:27 ! ATTENTION! NEWS! dr-xr-xr-x   1 user     group           0 Feb  4 09:40 !
Component_update
dr-xr-xr-x 1 user group 0 Jan 24 18:51 . dr-xr-xr-x 1 user group 0 Jan 24 18:51 .. dr-xr-xr-x 1 user group 0 Jan 21 09:38 1 dr-xr-xr-x 1 user group 0 Nov 8 11:20 2 dr-xr-xr-x 1 user group 0 Sep 30 15:39 A-TRANS dr-xr-xr-x 1 user group 0 Dec 9 09:36 ARMENIA dr-xr-xr-x 1 user group 0 Nov 8 2009 ARMOPD(WIN) dr-xr-xr-x 1 user group 0 Jan 13 17:18 ARM_CD dr-xr-xr-x 1 user group 0 Nov 25 10:55 DB2_Freight _express

If the Short Form Output option is selected, the function returns a string array consisting only of a list of files and directories included in the specified directory on the FTP server.

The returned result is:

  • A string array of a list of files and directories. If there are no files or directories in the specified directory, a zero-length string array is returned.

public string[] ListNameFile (string PathFTP, bool Files)

Generates a list of files or directories located in the specified PathFTP on the FTP server.

Options:

  • PathFTP – path to the directory on the FTP server;
  • Files—Defines the contents of the list. Files = true returns a list of files, otherwise a directory list.

The returned result is:

  • A string array of a list of files or directories. If there are no files or directories in the specified directory on the FTP server, a zero-length string array is returned.

Note:

  • If there are spaces inside the file or directory name, the string is enclosed in double quotation marks. The PathFTP path must have the final character "\".

Class Properties

public string Err { get; }

Returns a string with an error message that occurred while working with FTP, or an empty string if there are no errors.

Example of using the FTP class

 
 
Code:
//****************************************
An example of using the FTP


using System class;
using SF;

…

create an FTP object
oSF = new FTP("10.240.3.110", 21, "anonymous", "alex@mail.ru");

Write a file from the local computer to the FTP
if server (oSF. UploadFile(@"Program\User", @"d:\temp\alfa.doc"))
Console. WriteLine("File written");
else
Console. WriteLine("Error! " + oSF. Err);

Upload a file from an FTP server to the local computer
if (oSF. DownloadFile(@"Program\User\alfa.doc", @"d:\temp\alfa.doc"))
Console. WriteLine("File uploaded");
else
Console. WriteLine("Error! " + oSF. Err);

Get a list of files and directories at the specified path
string[] ListDir = oSF. ListDirectory(@"Program\User", false);
if (ListDir. Length > 0) {
Console. WriteLine("File List:");
for (int i = 0; i < ListDir. Length; i++)
Console. WriteLine(ListDir[i]);
}
else
Console. WriteLine("List is empty");

get only a list of files
string[] ListFile = oSF. ListNameFile(@"Program\User", true);
if (ListFile. Length > 0) {
Console. WriteLine("File List:");
for (int i = 0; i < ListFile. Length; i++)
Console. WriteLine(ListFile[i]);
}
else
Console. WriteLine("List is empty");

&hellip
;

Class code

 
Code:
 
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;


namespace SF {

public struct FileStruct {
public string Flags;
public string Owner;
public string Group;
public bool IsDirectory;
public DateTime CreateTime;
public string Name;
}

public enum FileListStyle {
UnixStyle,
WindowsStyle,
Unknown
}

Class for working with FTP
public class FTP {
private string Host;
private int Port;
private string User;
private string Password;
private string Error;


* Function: FTP
* Notes: Class
Designer *

public FTP (string Host, int Port, string User, string Password) {
this. Host = Host;
this. Port = Port;
this. User = User;
this. Password = Password;
this. Error = "";
}

End of FTP **********


* Function: UploadFile
* Notes: Write file to FTP
*

public bool UploadFile ( string PathFTP, string NameFile) {
FileInfo InfoFile = new FileInfo(NameFile);
FtpWebRequest Request;
string UploadUri = "";

this. Error = "";
if (PathFTP == "")
UploadUri = "ftp://" + this. Host + ":" + this. Port. ToString() + "/" +
InfoFile. Name;
else
UploadUri = "ftp://" + this. Host + ":" + this. Port. ToString() + "/" +
PathFTP + "/" + InfoFile. Name;
Request = (FtpWebRequest)FtpWebRequest. Create(UploadUri);
Request. Credentials = new NetworkCredential(this. User, this. Password);
Request. KeepAlive = false;
Request. Method = WebRequestMethods. Ftp. UploadFile;
Request. UseBinary = true;
Request. ContentLength = InfoFile. Length;
int BuffLength = 2048;
byte[] Buff = new byte[BuffLength];
int ContentLen;
FileStream FS = InfoFile. OpenRead();
try {
Stream Strm = Request. GetRequestStream();
ContentLen = FS. Read(Buff, 0, BuffLength);
while (ContentLen != 0) {
Strm. Write(Buff, 0, ContentLen);
ContentLen = FS. Read(Buff, 0, BuffLength);
}
close all Strm threads
. Close();
FS. Close();
return true;
}
catch (Exception e) {
this. Error = e. Message;
return false;
}
}

End of UploadFile ***********


* Function: DownloadFile
* Notes: Downloads the NameFileFTP file from the FTP server and writes
* the downloaded file to the local computer with name NameFileLocal.
//*

public bool DownloadFile (string NameFileFTP, string NameFileLocal) {
FtpWebRequest Request;
string DownloadUri = "";

try {
FileStream OutputStream = new FileStream(NameFileLocal, FileMode. Create);
this. Error = "";
DownloadUri = "ftp://" + this. Host + ":" + this. Port. ToString() + "/" +
NameFileFTP;
Request = (FtpWebRequest)FtpWebRequest. Create(DownloadUri);
Request. Method = WebRequestMethods. Ftp. DownloadFile;
Request. UseBinary = true;
Request. Credentials = new NetworkCredential(this. User, this. Password);
FtpWebResponse Response = (FtpWebResponse)Request. GetResponse();

Stream FtpStream = Response. GetResponseStream();
long cl = Response. ContentLength;
int BufferSize = 2048;
int ReadCount;
byte[] Buffer = new byte[BufferSize];

ReadCount = FtpStream. Read(Buffer, 0, BufferSize);
while (ReadCount > 0) {
OutputStream. Write(Buffer, 0, ReadCount);
ReadCount = FtpStream. Read(Buffer, 0, BufferSize);
}
close all FtpStream streams
. Close();
OutputStream. Close();
Response. Close();
return true;
}
catch (Exception e) {
this. Error = e. Message;
return false;
}
}

End of DownloadFile ***********


* Function: ListDirectory
* Notes: Returns a string array of a list of files and directories *
located in the specified directory
//*

public string[] ListDirectory (string PathFTP, bool Details) {
string[] DownloadFiles;
StringBuilder Result = new StringBuilder();
FtpWebRequest Request;
string UriFTP = "";

try {
this.Error = "";
if (PathFTP == "")
UriFTP = "ftp://" + this. Host + ":" + this. Port. ToString() + "/";
else
UriFTP = "ftp://" + this. Host + ":" + this. Port. ToString() + "/" +
PathFTP;
Request = (FtpWebRequest)FtpWebRequest. Create(UriFTP);
Request. UseBinary = true;
Request. Credentials = new NetworkCredential(this. User, this. Password);
if (Details)
Request. Method = WebRequestMethods. Ftp. ListDirectoryDetails;
else
Request. Method = WebRequestMethods. Ftp. ListDirectory;
WebResponse Response = Request. GetResponse();
StreamReader Reader = new StreamReader(Response. GetResponseStream(),
Encoding. GetEncoding(1251));
string Line = Reader. ReadLine();
while (Line != null) {
Result. Append(Line);
Result. Append("\n");
Line = Reader. ReadLine();
}
Reader. Close();
Response. Close();
if (Result. Length != 0) {
Result. Remove(Result. ToString(). LastIndexOf('\n'), 1);
return Result. ToString(). Split('\n');
}
else {
return (new string[0]);
}
}
catch (Exception e) {
this. Error = e. Message;
DownloadFiles = new string[0];
return DownloadFiles;
}
}

End of ListDirectory ***********


* Function: ListNameFile
* Notes: Returns a string array of a list of
files or directories * located in the specified directory
//*

public string[] ListNameFile (string PathFTP, bool Files) {
FtpWebRequest Request;
string[] ListFile;
string UriFTP = "";
int NumDir = 0;
int NumFile = 0;

try {
this. Error = "";
if (PathFTP == "")
UriFTP = "ftp://" + this. Host + ":" + this. Port. ToString() + "/";
else
UriFTP = "ftp://" + this. Host + ":" + this. Port. ToString() + "/" +
PathFTP;
Request = (FtpWebRequest)FtpWebRequest. Create(UriFTP);
Request. UseBinary = true;
Request. Credentials = new NetworkCredential(this. User, this. Password);
Request. Method = WebRequestMethods. Ftp. ListDirectoryDetails;
WebResponse Response = Request. GetResponse();
StreamReader Reader = new StreamReader(Response. GetResponseStream(),
Encoding. GetEncoding(1251));
string Datastring = Reader. ReadToEnd();
Reader. Close();
Response. Close();
FileStruct[] List = GetList(Datastring);
foreach (FileStruct thisstruct in List) {
if (thisstruct. IsDirectory)
NumDir++;
else
NumFile++;
}
if (Files) {
ListFile = new string[NumFile];
if (NumFile == 0)
return ListFile;
}
else {
ListFile = new string[NumDir];
if (NumDir == 0)
return ListFile;
}
int j = 0;
for (int i = 0; i < List. Length; i++) {
if (Files && ! List[i]. IsDirectory)
ListFile[j++] = List[i]. Name;
else if (! Files && List[i]. IsDirectory)
ListFile[j++] = List[i]. Name;
}
return ListFile;
}
catch (Exception e) {
this. Error = e. Message;
return new string[0];
}
}

//*** End of ListNameFile ***********

//*************************************************************
//* Function: GetList
//*

private FileStruct[ ] GetList (string DataStr) {
List<FileStruct> ListArray = new List<FileStruct>();
string[] DataRec = DataStr. Split('\n');
FileListStyle DirListStyle = GetFileListStyle(DataRec);
foreach (string s in DataRec) {
if (DirListStyle != FileListStyle. Unknown && s != "") {
FileStruct FS = new FileStruct();
FS. Name = ".." ;
switch (DirListStyle) {
case FileListStyle. UnixStyle:
FS = ParseFileStructUnixStyle(s);
break;
case FileListStyle. WindowsStyle:
FS = ParseFileStructWindowsStyle(s);
break;
}
if (! (FS. Name == "." || FS. Name == ".." )) {
ListArray. Add(FS);
}
}
}
return ListArray. ToArray();
}

//*** End of GetList ***********

//*************************************************************
//* Function: ParseFileStructUnixStyle
//*

private FileStruct ParseFileStructUnixStyle ( string Record) {
// dr-xr-xr-x 1 owner group 0 Nov 25 2002 bussys
FileStruct FS = new FileStruct();
string ProcStr = Record. Trim();
if (ProcStr. ToLower() == "total 0") {
FS. Name = "";
return FS;
}
FS. Flags = ProcStr. Substring(0, 9);
FS. IsDirectory = (FS. Flags[0] == 'd');
ProcStr = (ProcStr. Substring(11)). Trim();
CutSubstr(ref ProcStr, ' ', 0);
FS. Owner = CutSubstr(ref ProcStr, ' ', 0);
FS. Group = CutSubstr(ref ProcStr, ' ', 0);
CutSubstr(ref ProcStr, ' ', 0);
try {
FS. CreateTime = DateTime. Parse(CutSubstr(ref ProcStr, ' ', 8));
}
catch {
FS. CreateTime = DateTime. Now;
}
if (ProcStr. IndexOf(" ") > 0)
FS. Name = "\"" + ProcStr + "\"";
else
FS. Name = ProcStr;
return FS;
}

//*** End of ParseFileStructUnixStyle ***********

//*************************************************************
//* Function: ParseFileStructWindowsStyle
//*

private FileStruct ParseFileStructWindowsStyle (string Record) {
02-03-04 07:46PM <DIR> Append
FileStruct FS = new FileStruct();
string ProcStr = Record. Trim();
string DateStr = ProcStr. Substring(0, 8);
ProcStr = (ProcStr. Substring(8, ProcStr. Length - 8)). Trim();
string TimeStr = ProcStr. Substring(0, 7);
ProcStr = (ProcStr. Substring(7, ProcStr. Length - 7)). Trim();
try {
FS. CreateTime = DateTime. Parse(DateStr + " " + TimeStr);
}
catch {
FS. CreateTime = DateTime. Now;
}
if (ProcStr. Substring(0, 5) == "<DIR>") {
FS. IsDirectory = true;
ProcStr = (ProcStr. Substring(5, ProcStr. Length - 5)). Trim();
}
else {
string[] StrS = ProcStr. Split(new char[] { ' ' },
StringSplitOptions. RemoveEmptyEntries);
file name with spaces inside, border the string with double quotation
marks if (StrS. Length > 2) {
ProcStr = "";
for (int i = 1; i < StrS. Length; i++)
ProcStr = ProcStr + StrS[i] + " ";
ProcStr = "\"" + ProcStr. Trim() + "\"";
}
else
ProcStr = StrS[1]. Trim();
FS. IsDirectory = false;
}
FS. Name = ProcStr;
return FS;
}

//*** End of ParseFileStructWindowsStyle ***********

//*************************************************************
//* Function: GetFileListStyle
//* Notes:
//*

public FileListStyle GetFileListStyle (string[] RecList) {
foreach (string s in RecList) {
if (s. Length > 10
&& Regex. IsMatch(s. Substring(0, 10),
"(-|d)(-|r)(-|w)(-|x)(-|r)(-|w)(-|x)(-|r)(-|w)(-|x)")) {
return FileListStyle. UnixStyle;
}
else if (s. Length > 8
&& Regex. IsMatch(s. Substring(0, 8),
"[0-9][0-9]-[0-9][0-9]-[0-9][0-9]")) {
return FileListStyle. WindowsStyle;
}
}
return FileListStyle. Unknown;
}

//*** End of GetFileListStyle ***********

//*************************************************************
//* Function: CutSubstr
//* Notes:
//*

private string CutSubstr (ref string s, char c, int startIndex) {
int pos1 = s. IndexOf(c, startIndex);
string retString = s. Substring(0, pos1);
s = (s. Substring(pos1)). Trim();
return retString;
}

End of CutSubstr ***********

get the error
message public string Err {
get {
return this. Error
;
    }
  }

}

}