public class FtpHelper
{
public static readonly FtpHelper Instance = new FtpHelper();
/// <summary>
/// Get the file name
/// </summary>
/// <param name="ftpPath">ftp path</param>
/// <returns></returns>
public string[] GetFilePath(string userId, string pwd, string ftpPath)
{
string[] downloadFiles;
StringBuilder result = new StringBuilder();
FtpWebRequest reqFTP;
try
{
reqFTP = (FtpWebRequest)(new Uri(ftpPath));
= true;
= new NetworkCredential(userId, pwd);
= ;
= false;
WebResponse response = ();
StreamReader reader = new StreamReader(());
string line = ();
While (line != null)
{
(line);
("\n");
line = ();
}
(().LastIndexOf('\n'), 1);
();
();
return ().Split('\n');
}
catch (Exception ex)
{
downloadFiles = null;
return downloadFiles;
}
}
//FTP upload function
public void Upload(string userId, string pwd, string filename, string ftpPath)
{
FileInfo fileInf = new FileInfo(filename);
FtpWebRequest reqFTP;
// Create FtpWebRequest object based on uri
reqFTP = (FtpWebRequest)(new Uri(ftpPath + ));
// ftp username and password
= new NetworkCredential(userId, pwd);
= false;
// Default is true, the connection will not be closed
// Execute after a command
= false;
// Specify what command to execute
= ;
// Specify the data transfer type
= true;
// Notify the server file size when uploading
= ;
// Set the buffer size to 2kb
int buffLength = 2048;
byte[] buff = new byte[buffLength];
int contentLen;
// Open a file stream () to read the uploaded file
FileStream fs = ();
try
{
// Write the uploaded file to the stream
Stream strm = ();
// 2kb of file stream per read
contentLen = (buff, 0, buffLength);
// The streaming content has not ended
While (contentLen != 0)
{
// Write content from file stream to upload stream
(buff, 0, contentLen);
contentLen = (buff, 0, buffLength);
}
// Close two streams
();
();
}
catch (Exception ex)
{
}
}
public void Delete(string userId, string pwd, string ftpPath, string fileName)
{
FtpWebRequest reqFTP;
try
{
reqFTP = (FtpWebRequest)(new Uri(ftpPath + fileName));
= ;
= true;
= new NetworkCredential(userId, pwd);
= false;
FtpWebResponse listResponse = (FtpWebResponse)();
string sStatus = ;
}
catch (Exception ex)
{
throw ex;
}
}
//Function of downloading files from ftp server
public void Download(string userId, string pwd, string ftpPath, string filePath, string fileName)
{
FtpWebRequest reqFTP;
try
{
FileStream outputStream = new FileStream(filePath + "\\" + fileName, );
reqFTP = (FtpWebRequest)(new Uri(ftpPath + fileName));
= ;
= true;
= new NetworkCredential(userId, pwd);
= false;
FtpWebResponse response = (FtpWebResponse)();
Stream ftpStream = ();
long cl = ;
int bufferSize = 2048;
int readCount;
byte[] buffer = new byte[bufferSize];
readCount = (buffer, 0, bufferSize);
while (readCount > 0)
{
(buffer, 0, readCount);
readCount = (buffer, 0, bufferSize);
}
();
();
();
}
catch (Exception ex)
{
throw ex;
}
}
}