Skip to content

Instantly share code, notes, and snippets.

@MarshalOfficial
Created October 21, 2015 10:51
Show Gist options
  • Save MarshalOfficial/277c3f731609720ba598 to your computer and use it in GitHub Desktop.
Save MarshalOfficial/277c3f731609720ba598 to your computer and use it in GitHub Desktop.
FTPManger class written in c# implements basic ftp site operations like download and upload files and etc...
using System;
using System.IO;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net;
namespace Marshal.Framework.NetworkUtility
{
/// <summary>
/// this class implement ftp base operations like download , upload , etc ...
/// </summary>
public class FTPManager
{
#region [Variables]
internal string ftpServerIP;
internal string ftpUserID;
internal string ftpPassword;
#endregion
#region [CTOR]
public FTPManager(string FtpServerIP, string FtpUserID, string FtpPassword)
{
ftpServerIP = FtpServerIP;
ftpUserID = FtpUserID;
ftpPassword = FtpPassword;
}
#endregion
#region [Methods]
/// <summary>
/// Method to upload specified file to the specified FTP Server
/// </summary>
/// <param name="filename">full file name on local system like : "C:\Temp\TestFile.zip"</param>
/// <param name="FtpMiddlePath">middle folder in ftp path like "TestDir" folder in this path : ftp://192.168.1.2/TestDir/TestFile.zip</param>
public void Upload(string filename,string FtpMiddlePath="")
{
FileInfo fileInf = new FileInfo(filename);
//string uri = "ftp://" + ftpServerIP + "/" + fileInf.Name;
string uri = ftpServerIP + fileInf.Name;
FtpWebRequest reqFTP;
// Create FtpWebRequest object from the Uri provided
reqFTP = !string.IsNullOrEmpty(FtpMiddlePath) ? (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + ftpServerIP + "/" + FtpMiddlePath + "/" + fileInf.Name)) : (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + ftpServerIP +"/"+ fileInf.Name));
// Provide the WebPermission Credintials
reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
// By default KeepAlive is true, where the control connection is not closed
// after a command is executed.
reqFTP.KeepAlive = false;
// Specify the command to be executed.
reqFTP.Method = WebRequestMethods.Ftp.UploadFile;
// Specify the data transfer type.
reqFTP.UseBinary = true;
// Notify the server about the size of the uploaded file
reqFTP.ContentLength = fileInf.Length;
// The buffer size is set to 2kb
int buffLength = 2048;
byte[] buff = new byte[buffLength];
int contentLen;
// Opens a file stream (System.IO.FileStream) to read the file to be uploaded
FileStream fs = fileInf.OpenRead();
try
{
// Stream to which the file to be upload is written
Stream strm = reqFTP.GetRequestStream();
// Read from the file stream 2kb at a time
contentLen = fs.Read(buff, 0, buffLength);
// Till Stream content ends
while (contentLen != 0)
{
// Write Content from the file stream to the FTP Upload Stream
strm.Write(buff, 0, contentLen);
contentLen = fs.Read(buff, 0, buffLength);
}
// Close the file stream and the Request Stream
strm.Close();
fs.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Upload Error");
}
}
/// <summary>
/// Method to delete specified from FTP Server
/// </summary>
/// <param name="fileName">full file name to be Deleted From FTP</param>
/// <param name="ftpMiddlePath">Middle Dir In Target Path</param>
public void DeleteFTP(string fileName,string ftpMiddlePath="")
{
try
{
string uri = ftpServerIP + fileName;
FtpWebRequest reqFTP;
reqFTP = !string.IsNullOrEmpty(ftpMiddlePath) ? (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + ftpServerIP + "/" + ftpMiddlePath + "/" + fileName)) : (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + ftpServerIP + "/" + fileName));
reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
reqFTP.KeepAlive = false;
reqFTP.Method = WebRequestMethods.Ftp.DeleteFile;
string result = String.Empty;
FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
long size = response.ContentLength;
Stream datastream = response.GetResponseStream();
StreamReader sr = new StreamReader(datastream);
result = sr.ReadToEnd();
sr.Close();
datastream.Close();
response.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "FTP 2.0 Delete");
}
}
/// <summary>
/// Show All Files Details In That Ftp Path , Details like '<DIR>' and ...
/// </summary>
/// <returns></returns>
public string[] GetFilesDetailList()
{
string[] downloadFiles;
try
{
StringBuilder result = new StringBuilder();
FtpWebRequest ftp;
ftp = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + ftpServerIP + "/"));
ftp.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
ftp.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
WebResponse response = ftp.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream());
string line = reader.ReadLine();
while (line != null)
{
result.Append(line);
result.Append("\n");
line = reader.ReadLine();
}
result.Remove(result.ToString().LastIndexOf("\n"), 1);
reader.Close();
response.Close();
return result.ToString().Split('\n');
//MessageBox.Show(result.ToString().Split('\n'));
}
catch (Exception ex)
{
System.Windows.Forms.MessageBox.Show(ex.Message);
downloadFiles = null;
return downloadFiles;
}
}
/// <summary>
/// Get All File Lists in That Ftp Path.
/// </summary>
/// <returns></returns>
public string[] GetFileList()
{
string[] downloadFiles;
StringBuilder result = new StringBuilder();
FtpWebRequest reqFTP;
try
{
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + ftpServerIP + "/"));
reqFTP.UseBinary = true;
reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
reqFTP.Method = WebRequestMethods.Ftp.ListDirectory;
WebResponse response = reqFTP.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream());
//MessageBox.Show(reader.ReadToEnd());
string line = reader.ReadLine();
while (line != null)
{
result.Append(line);
result.Append("\n");
line = reader.ReadLine();
}
result.Remove(result.ToString().LastIndexOf('\n'), 1);
reader.Close();
response.Close();
//MessageBox.Show(response.StatusDescription);
return result.ToString().Split('\n');
}
catch (Exception ex)
{
System.Windows.Forms.MessageBox.Show(ex.Message);
downloadFiles = null;
return downloadFiles;
}
}
/// <summary>
/// Download Form Ftp Site
/// </summary>
/// <param name="fullfilePath">full file path of local system to save file like : D:\Jacks\110.exe</param>
/// <param name="FullFilePathOnFtp">Full Name Of FTP File To Download like That "Test/AdditionalDir/110.exe"</param>
public void Download(string fullfilePath, string FullFilePathOnFtp)
{
FtpWebRequest reqFTP;
try
{
FileStream outputStream = new FileStream(fullfilePath, FileMode.Create);
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + ftpServerIP + FullFilePathOnFtp));
reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
reqFTP.UseBinary = true;
reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
FtpWebResponse response = (FtpWebResponse)reqFTP.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);
}
ftpStream.Close();
outputStream.Close();
response.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
/// <summary>
/// Get Specific File Size In Ftp Site
/// </summary>
/// <param name="filename">Full Name Of Target File In Ftp Site like That "Test/AdditionalDir/110.exe" </param>
/// <returns></returns>
public long GetFileSize(string filename)
{
FtpWebRequest reqFTP;
long fileSize = 0;
try
{
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + ftpServerIP + "/" + filename));
reqFTP.Method = WebRequestMethods.Ftp.GetFileSize;
reqFTP.UseBinary = true;
reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
Stream ftpStream = response.GetResponseStream();
fileSize = response.ContentLength;
ftpStream.Close();
response.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
return fileSize;
}
/// <summary>
/// Rename Specific File In Ftp Site
/// </summary>
/// <param name="currentFilename">full name of target file like : "Test/AdditionalDir/110.exe" </param>
/// <param name="newFilename">new name for target file</param>
/// <param name="ftpMiddlePath">Middle Folder In Ftp Like Test In This Path : ftp://192.168.1.2/Test/110.exe</param>
public void Rename(string currentFilename, string newFilename,string ftpMiddlePath="")
{
FtpWebRequest reqFTP;
try
{
reqFTP = !string.IsNullOrEmpty(ftpMiddlePath) ? (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + ftpServerIP + "/" + ftpMiddlePath + "/" + currentFilename)) : (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + ftpServerIP + "/" + currentFilename));
reqFTP.Method = WebRequestMethods.Ftp.Rename;
reqFTP.RenameTo = newFilename;
reqFTP.UseBinary = true;
reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
Stream ftpStream = response.GetResponseStream();
ftpStream.Close();
response.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
/// <summary>
/// Make Directory In Ftp Site
/// </summary>
/// <param name="dirName"></param>
public void MakeDir(string dirName)
{
FtpWebRequest reqFTP;
try
{
// dirName = name of the directory to create.
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + ftpServerIP + "/" + dirName));
reqFTP.Method = WebRequestMethods.Ftp.MakeDirectory;
reqFTP.UseBinary = true;
reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
Stream ftpStream = response.GetResponseStream();
ftpStream.Close();
response.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
#endregion
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment