patbef-ServiceInside/Publisher/Services/FTP.cs

261 lines
8.5 KiB
C#

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace Publisher.Services
{
public class FTP
{
protected string FtpUser { get; set; }
protected string FtpPass { get; set; }
protected string FtpServerUrl { get; set; }
protected string DirPathToUpload { get; set; }
protected string BaseDirectory { get; set; }
protected string Dirname { get; set; }
public FTP(string ftpuser, string ftppass, string ftpserverurl, string baseDir, string dirpathtoupload)
{
this.FtpPass = ftppass;
this.FtpUser = ftpuser;
this.FtpServerUrl = ftpserverurl;
this.DirPathToUpload = dirpathtoupload;
this.BaseDirectory = baseDir;
this.Dirname = Path.GetFileName(dirpathtoupload);
}
public void UploadDirectory()
{
// rename the old folder version (if exist)
RenameDir(Dirname);
// create a parent folder on server
CreateDir(Dirname);
// upload the files in the most external directory of the path
UploadAllFolderFiles(DirPathToUpload, Dirname);
// loop trough all files in subdirectories
foreach (string dirPath in Directory.GetDirectories(DirPathToUpload, "*", SearchOption.AllDirectories))
{
// create the folder
CreateDir(dirPath.Substring(dirPath.IndexOf(Dirname), dirPath.Length - dirPath.IndexOf(Dirname)));
UploadAllFolderFiles(dirPath, dirPath.Substring(dirPath.IndexOf(Dirname), dirPath.Length - dirPath.IndexOf(Dirname)));
}
}
private void UploadAllFolderFiles(string localpath, string remotepath)
{
string[] files = Directory.GetFiles(localpath);
// get only the filenames and concat to remote path
foreach (string file in files)
{
// full remote path
var fullremotepath = remotepath + "\\" + Path.GetFileName(file);
// local path
var fulllocalpath = Path.GetFullPath(file);
// upload to server
Upload(fulllocalpath, fullremotepath);
}
}
public List<String> GetDirectories(string dirname)
{
List<String> result = new List<string>();
var path = "ftp://" + FtpServerUrl + "/" + dirname;
string serverUri = path;
try
{
string pattern =
@"^([\w-]+)\s+(\d+)\s+(\w+)\s+(\w+)\s+(\d+)\s+" +
@"(\w+\s+\d+\s+\d+|\w+\s+\d+\s+\d+:\d+)\s+(.+)$";
Regex regex = new Regex(pattern);
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(serverUri);
request.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
request.Proxy = null;
request.Credentials = new NetworkCredential(FtpUser, FtpPass);
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
Stream str = response.GetResponseStream();
StreamReader sr = new StreamReader(str);
while (!sr.EndOfStream)
{
string checkString = sr.ReadLine();
if (checkString.Trim() != "." && checkString.Trim() != "..")
{
Match match = regex.Match(checkString);
if (match.Success)
{
string name = match.Groups[7].Value;
long size = 0;
long.TryParse(match.Groups[5].Value, out size);
result.Add(name + " - " + ((float)(size / 1024 / 1024 / 1024)).ToString("#0.00") + " GB");
}
else
{
result.Add(checkString.TrimStart(' '));
}
}
}
}
catch (Exception ex)
{
}
return result;
}
public bool DeleteDirectory(string dirname)
{
bool result = false;
var path = "ftp://" + FtpServerUrl + "/" + dirname;
string serverUri = path;
try
{
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(serverUri);
request.Method = WebRequestMethods.Ftp.RemoveDirectory;
request.Proxy = null;
request.Credentials = new NetworkCredential(FtpUser, FtpPass);
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
Stream str = response.GetResponseStream();
result = true;
}
catch (Exception ex)
{
}
return result;
}
public bool DeleteFile(string filename)
{
bool result = false;
var path = "ftp://" + FtpServerUrl + "/" + filename;
string serverUri = path;
try
{
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(serverUri);
request.Method = WebRequestMethods.Ftp.DeleteFile;
request.Proxy = null;
request.Credentials = new NetworkCredential(FtpUser, FtpPass);
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
Stream str = response.GetResponseStream();
result = true;
}
catch (Exception ex)
{
}
return result;
}
public bool CreateDir(string dirname)
{
try
{
WebRequest request = WebRequest.Create("ftp://" + FtpServerUrl + "/" + this.BaseDirectory + "/" + dirname);
request.Method = WebRequestMethods.Ftp.MakeDirectory;
request.Proxy = new WebProxy();
request.Credentials = new NetworkCredential(FtpUser, FtpPass);
using (var resp = (FtpWebResponse)request.GetResponse())
{
if (resp.StatusCode == FtpStatusCode.PathnameCreated)
{
return true;
}
else
{
return false;
}
}
}
catch
{
return false;
}
}
public void Upload(string filepath, string targetpath)
{
try
{
using (WebClient client = new WebClient())
{
client.Credentials = new NetworkCredential(FtpUser, FtpPass);
client.Proxy = null;
var fixedpath = targetpath.Replace(@"\", "/");
client.UploadFile("ftp://" + FtpServerUrl + "/" + BaseDirectory + "/" + fixedpath, WebRequestMethods.Ftp.UploadFile, filepath);
}
}
catch (Exception ex)
{
}
}
public bool RenameDir(string dirname)
{
var path = "ftp://" + FtpServerUrl + "/" + this.BaseDirectory + "/" + dirname;
string serverUri = path;
try
{
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(serverUri);
request.Method = WebRequestMethods.Ftp.Rename;
request.Proxy = null;
request.Credentials = new NetworkCredential(FtpUser, FtpPass);
// change the name of the old folder the old folder
request.RenameTo = dirname + "_backups___" + DateTime.Now.ToString("yyyyMMddHHmmss");
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
using (var resp = (FtpWebResponse)request.GetResponse())
{
if (resp.StatusCode == FtpStatusCode.FileActionOK)
{
return true;
}
else
{
return false;
}
}
}
catch
{
return false;
}
}
}
}