static void Main() { var testConnection = new FtpConnection("SERVER", "USER", "PASSWORD"); var testFileLocation = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory) + "/testFile.txt"; var testByteArray = File.ReadAllBytes(testFileLocation); testConnection.UploadFile(testByteArray, "testName", "/SOMEPATH"); }
/// <summary> /// Initializes a new instance of the <see cref="MlstCommandHandler"/> class. /// </summary> /// <param name="connection">The FTP connection this command handler is created for.</param> public MlstCommandHandler(FtpConnection connection) : base(connection, "MLST", "MLSD") { connection.Data.ActiveMlstFacts.Clear(); foreach (var knownFact in _knownFacts) connection.Data.ActiveMlstFacts.Add(knownFact); }
private static string FeatureStatus(FtpConnection connection) { var result = new StringBuilder(); result.Append("MLST "); foreach (var fact in _knownFacts) { result.AppendFormat("{0}{1};", fact, connection.Data.ActiveMlstFacts.Contains(fact) ? "*" : string.Empty); } return result.ToString(); }
public bool FTPTransferHHTToPC(string hostIP, bool checkpermissionMode) { using (FtpConnection ftp = new FtpConnection(hostIP, userFTP, passwordFTP)) { try { ftp.Open(); /* Open the FTP connection */ ftp.Login(userFTP, passwordFTP); /* Login using previously provided credentials */ string remoteFile = ""; string localFile = ""; if (checkpermissionMode) { remoteFile = HHTDBPath + validateDBName; localFile = new System.IO.FileInfo(System.Reflection.Assembly.GetExecutingAssembly().Location).DirectoryName + "\\" + validateDBName; } else { remoteFile = HHTDBPath + DBName; localFile = new System.IO.FileInfo(System.Reflection.Assembly.GetExecutingAssembly().Location).DirectoryName + "\\" + DBName; } if (ftp.FileExists(remoteFile)) /* check that a file exists */ { ftp.GetFile(remoteFile, localFile, false); /* download /incoming/file.txt as file.txt to current executing directory, overwrite if it exists */ return(true); } else { return(false); } } catch (Exception ex) { //Console.WriteLine(String.Format("FTP Error: {0} {1}", e.ErrorCode, e.Message)); log.Error(String.Format("Exception : {0}", ex.StackTrace)); return(false); } } }
private bool PutFile(FtpConnection ftp, string file) { string ftpPart = file.Remove(0, file.IndexOf(@"Interface\AddOns\") + (@"Interface\AddOns\").Length); string folderName = ftpPart.Remove(ftpPart.LastIndexOf(@"\")); string fileName = ftpPart.Remove(0, ftpPart.LastIndexOf(@"\") + 1); if (!currentDir.Equals(folderName)) { ftp.SetCurrentDirectory(@"\" + folderName); currentDir = folderName; currentDirFileInfo = ftp.GetFiles(); } FileInfo localFileInfo = new FileInfo(file); FtpFileInfo ftpFileInfo = null; foreach (FtpFileInfo info in currentDirFileInfo) { if (info.Name.Equals(fileName)) { ftpFileInfo = info; } } if (ftpFileInfo == null) { ftp.PutFile(file, fileName); return(true); } else { DateTime ftpTime = ftpFileInfo.LastWriteTimeUtc ?? DateTime.MinValue; if (ftpTime < localFileInfo.LastWriteTimeUtc) { ftp.PutFile(file, fileName); return(true); } } return(false); }
/// <summary> /// Upload Files /// </summary> private void UploadFiles() { if (this.FileNames == null) { this.Log.LogError("The required fileNames attribute has not been set for FTP."); return; } using (FtpConnection ftpConnection = this.CreateFtpConnection()) { this.LogTaskMessage("Uploading Files"); if (!string.IsNullOrEmpty(this.WorkingDirectory)) { this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Setting Local Directory: {0}", this.WorkingDirectory)); FtpConnection.SetLocalDirectory(this.WorkingDirectory); } ftpConnection.LogOn(); if (!string.IsNullOrEmpty(this.RemoteDirectoryName)) { this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Setting Current Directory: {0}", this.RemoteDirectoryName)); ftpConnection.SetCurrentDirectory(this.RemoteDirectoryName); } foreach (string fileName in this.FileNames.Select(item => item.ItemSpec)) { try { if (File.Exists(fileName)) { this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Uploading: {0}", fileName)); ftpConnection.PutFile(fileName); } } catch (FtpException ex) { this.Log.LogError(string.Format(CultureInfo.CurrentCulture, "There was an error uploading file: {0}. The Error Details are \"{1}\" and error code is {2} ", fileName, ex.Message, ex.ErrorCode)); } } } }
private void btnIISftp_login_Click(object sender, EventArgs e) { try { this.iis_ftpconnection = this.Get171Connection(); this.iis_ftpconnection.Login(); this.btnIISftp_cwd.Enabled = true; this.btnIISftp_files.Enabled = true; this.btnIISftp_pwd.Enabled = true; this.btnIISftp_login.Enabled = false; } catch (Exception ex) { Console.WriteLine("serv-u 登录失败" + ex.Message); this.btnIISftp_cwd.Enabled = false; this.btnIISftp_files.Enabled = false; this.btnIISftp_pwd.Enabled = true; this.btnIISftp_login.Enabled = true; } }
public void Execute(IActivityRequest request, IActivityResponse response) { String sourcePath = request.Inputs["Source File Path"].AsString(); String savePath = request.Inputs["Destination File Path"].AsString(); bool overwriteLocal = Convert.ToBoolean(request.Inputs["Overwrite Local File"].AsString()); using (FtpConnection ftp = new FtpConnection(settings.FtpServer, settings.Port, settings.UserName, settings.Password)) { ftp.Open(); ftp.Login(); if (ftp.FileExists(sourcePath)) { ftp.GetFile(sourcePath, savePath, overwriteLocal); } else { response.LogErrorMessage("File does not exist at " + sourcePath); } } }
/// <summary> /// Libera la instancia /// </summary> private void Release(bool waitReply) { FtpConnection connection = Connection; if (connection != null) { try { if (waitReply) { // Espera los resultados: // 226: ACK predeterminado // 150: Si el stream se abrió pero nunca se ha enviado nada, podemos salir sin problema Process(() => new Commands.FtpEmptyStreamCommand(connection, new int[] { 226, 150 }).Send()); } } finally { // en transferencias largas, puede que se haya cerrado el socket, sin embargo, // lo debemos señalar en el cliente } } }
private void GetFile() { string Newlocation = ""; string ftpusername = "******"; string ftppassword = "******"; string ip = "172.26.50.199"; int FtpPort = Convert.ToInt16("21"); string Actfile = "sample.txt"; int cnt = Actfile.LastIndexOf('.'); string Extn = Actfile.Substring(Actfile.LastIndexOf('.'), Actfile.Length - Actfile.LastIndexOf('.')); using (FtpConnection _ftp = new FtpConnection(ip, FtpPort, ftpusername, ftppassword)) { try { _ftp.Open(); _ftp.Login(); string Ftpfile = "Notifications\\sample.txt"; Newlocation = "D:\\Syed\\Downloaded"; _ftp.GetFile(Ftpfile, Newlocation + "\\" + "sample.txt", false); } catch (FtpException ex) { throw ex; } finally { _ftp.Close(); string strDURL = "D:\\Syed\\Downloaded\\sample.txt"; System.IO.FileInfo toDownload = new System.IO.FileInfo(strDURL); } } }
public static void getFile(ref string UserName, ref string PassWord, ref string ServerName, ref string FileName) { using (FtpConnection ftp = new FtpConnection("ServerName", "UserName", "PassWord")) { ftp.Open(); /* Open the FTP connection */ ftp.Login(); /* Login using previously provided credentials */ if (ftp.DirectoryExists("/incoming")) /* check that a directory exists */ { ftp.SetCurrentDirectory("/incoming"); /* change current directory */ } if (ftp.FileExists("/incoming/file.txt")) /* check that a file exists */ { ftp.GetFile("/incoming/file.txt", false); /* download /incoming/file.txt as file.txt to current executing directory, overwrite if it exists */ } //do some processing try { ftp.SetCurrentDirectory("/outgoing"); ftp.PutFile(@"c:\localfile.txt", "file.txt"); /* upload c:\localfile.txt to the current ftp directory as file.txt */ } catch (FtpException e) { Console.WriteLine(String.Format("FTP Error: {0} {1}", e.ErrorCode, e.Message)); } foreach (var dir in ftp.GetDirectories("/incoming/processed")) { Console.WriteLine(dir.Name); Console.WriteLine(dir.CreationTime); foreach (var file in dir.GetFiles()) { Console.WriteLine(file.Name); Console.WriteLine(file.LastAccessTime); } } } } // End getFile()
/// <summary> /// Inicializa el stream para utilizar (o no) SSL/TLS /// </summary> private void InitializeProtocol(FtpConnection connection, FtpTransportStream data) { switch (connection.Client.Protocol) { case FtpClient.FtpProtocol.Ftp: // Directo. Simplemente se limpian los datos data.LeaveSsl(); break; case FtpClient.FtpProtocol.FtpS: // ... se cambia a un túnel SSL data.UpgradeToSsl(connection.Client.ClientParameters.GetSslProtocol()); break; case FtpClient.FtpProtocol.FtpES: // informa primero sobre un canal limpio y después se cambia a SSL data.LeaveSsl(); new Commands.Server.FtpAuthCommand(connection).Send(); data.UpgradeToSsl(connection.Client.ClientParameters.GetSslProtocol()); break; default: throw new ArgumentOutOfRangeException(); } }
internal ResumeCapability Connect(FtpConnection connection, bool addTraceListener = true, EventHandler <FtpGetListingEventArgs> onGetListingDataReceived = null) { _ftpClient = new FtpClient { EnableThreadSafeDataConnections = false, DataConnectionType = connection.UsePassiveMode ? FtpDataConnectionType.PASV : FtpDataConnectionType.PORT, Host = connection.Address, Port = connection.Port }; if (addTraceListener) { FtpTrace.AddListener(TraceListener); } Connection = connection; _ftpClient.BeforeAuthentication += OnBeforeAuthentication; _ftpClient.Connected += OnConnected; if (onGetListingDataReceived != null) { _ftpClient.GetListingDataReceived += onGetListingDataReceived; } _ftpClient.Connect(); var resume = ResumeCapability.None; var r = FtpClient.Execute("APPE"); if (!r.Message.Contains("command not recognized")) { resume |= ResumeCapability.Append; } r = FtpClient.Execute("REST"); if (!r.Message.Contains("command not recognized")) { resume |= ResumeCapability.Restart; } return(resume); }
public bool FTPTransferPCToHHT(string hostIP) { using (FtpConnection ftp = new FtpConnection(hostIP, userFTP, passwordFTP)) { try { ftp.Open(); /* Open the FTP connection */ ftp.Login(userFTP, passwordFTP); /* Login using previously provided credentials */ string remoteFile = HHTDBPath + DBName; string localFile = new System.IO.FileInfo(System.Reflection.Assembly.GetExecutingAssembly().Location).DirectoryName + "\\" + DBName; ftp.PutFile(localFile, remoteFile); return(true); } catch (Exception ex) { //Console.WriteLine(String.Format("FTP Error: {0} {1}", e.ErrorCode, e.Message)); log.Error(String.Format("Exception : {0}", ex.StackTrace)); return(false); } } }
private void sendViaFTP() { string _remoteHost = "ftp.bfi.net.in"; string _remoteUser = "******"; string _remotePass = "******"; string source = @"C:\Users\snarasim\Downloads\test.pdf"; string destination = "/test.pdf"; using (FtpConnection ftp = new FtpConnection(_remoteHost, _remoteUser, _remotePass)) { try { ftp.Open(); // Open the FTP connection ftp.Login(); // Login using previously provided credentials ftp.PutFile(source, destination); MessageBox.Show("Done"); } catch (Exception e) { MessageBox.Show(e.Message); } } }
private static void DownloadFiles(ServerInfo server) { string tempFolder = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + Path.DirectorySeparatorChar + "MapUpdater"; ConnectionInfo connection = server.MinecraftConnection; if (connection.Type == ConnectionType.Ftp) { using (FtpConnection ftp = new FtpConnection(connection.Address, 21, connection.Username, connection.Password)) { ftp.Open(); ftp.Login(); ftp.SetCurrentDirectory(connection.WorldsFolder); if (ftp.GetCurrentDirectory() != connection.WorldsFolder) { Console.WriteLine("WorldsFolder does not exist on server"); } DownloadDirectory(ftp, server.World.Name, tempFolder + Path.DirectorySeparatorChar + server.World.Name); } } }
/// <summary> /// Delete given files from the FTP Directory /// </summary> private void DeleteFiles() { if (this.FileNames == null) { this.Log.LogError("The required FileNames attribute has not been set for FTP."); return; } using (FtpConnection ftpConnection = this.CreateFtpConnection()) { ftpConnection.LogOn(); this.LogTaskMessage("Deleting Files"); if (!string.IsNullOrEmpty(this.RemoteDirectoryName)) { this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Setting Current Directory: {0}", this.RemoteDirectoryName)); ftpConnection.SetCurrentDirectory(this.RemoteDirectoryName); } foreach (string fileName in this.FileNames.Select(item => item.ItemSpec)) { try { this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Deleting: {0}", fileName)); ftpConnection.DeleteFile(fileName); } catch (FtpException ex) { if (ex.Message.Contains("550")) { continue; } this.Log.LogError(string.Format(CultureInfo.CurrentCulture, "There was an error in deleting file: {0}. The Error Details are \"{1}\" and error code is {2} ", fileName, ex.Message, ex.ErrorCode)); } } } }
/// <summary> /// Abre un stream de datos en modo pasivo /// </summary> internal FtpPassiveStream Open(FtpConnection connection) { string host = null; int port = 0; bool passive = false; // Intenta pasar a modo pasivo (EPSV o PSV) if (connection.Server.Features.HasFeature("EPSV")) { passive = TransferExtendedPassiveMode(connection, ref host, ref port); } else { passive = TransferPassiveMode(connection, ref host, ref port); } // Si no ha podido pasar a modo pasivo o no se ha interpretado correctamente el host lanza una excepción if (!passive) { throw new Exceptions.FtpException("No se ha podido pasar a modo pasivo"); } if (string.IsNullOrEmpty(host)) { throw new Exceptions.FtpException("No se pudo obtener la dirección del host al pasar a modo pasivo"); } // Asigna el proxy if (connection.Client.ClientParameters.ProxyConnect != null) { Socket socket = connection.Client.ClientParameters.ProxyConnect(new DnsEndPoint(host, port)); if (socket != null) { return(new FtpPassiveStream(connection, socket)); } } // Abre la conexión de datos return(OpenDataStream(connection, host, port)); }
public bool connect(string user, string pass) { bool ret = false; logger.pushOperation("FTP.connect"); try { sFTP = new FtpConnection(host, port); sFTP.Open(); sFTP.Login(user, pass); ret = sFTP.DirectoryExists("/"); } catch (Exception e) { ret = false; logger.log("Erro ao conectar FTP: " + e.Message, Logger.LogType.ERROR, e, false); } finally { logger.releaseOperation(); } return(ret); }
private static void UploadMapImages(ServerInfo server) { string currentDirectory = Environment.CurrentDirectory; ConnectionInfo connection = server.WebConnection; if (connection.Type == ConnectionType.Ftp) { using (FtpConnection ftp = new FtpConnection(connection.Address, 21, connection.Username, connection.Password)) { ftp.Open(); ftp.Login(); ftp.SetCurrentDirectory(connection.ImagesFolder); if (ftp.GetCurrentDirectory() != connection.ImagesFolder) { Console.WriteLine("ImagesFolder does not exist on server"); } foreach (string file in Directory.GetFiles(Environment.CurrentDirectory, "*.png")) { ftp.PutFile(file); } } } }
public MainForm() { InitializeComponent(); _ftp = null; string currentDirectory = Directory.GetCurrentDirectory(); if (!Directory.Exists(currentDirectory = Path.Combine(currentDirectory.Substring(0, currentDirectory.LastIndexOf("bin", currentDirectory.Length - 1)), "ftproot"))) { Directory.CreateDirectory(currentDirectory); } if (!Directory.Exists(_directoryDownload = Path.Combine(currentDirectory, "download"))) { Directory.CreateDirectory(_directoryDownload); } if (!Directory.Exists(_directoryUpload = Path.Combine(currentDirectory, "upload"))) { Directory.CreateDirectory(_directoryUpload); } }
public void ClearFtp(FtpConnection ftp, string directory) { ftp.SetCurrentDirectory(directory); var dirs = ftp.GetDirectories(); foreach (var dir in dirs) { if ((dir.Name != ".") && (dir.Name != "..")) { ClearFtp(ftp, dir.Name); //Recursive call ftp.RemoveDirectory(dir.Name); } } foreach (var file in ftp.GetFiles()) { ftp.RemoveFile(file.Name); } if (ftp.GetCurrentDirectory() != "/") { ftp.SetCurrentDirectory(".."); } }
public void UploadOrders() { try { Xceed.Ftp.Licenser.LicenseKey = "FTN42-K40Z3-DXCGS-PYGA"; //Xceed.FileSystem.Licenser.LicenseKey = ""; if (!UploadWork) { try { UploadWork = true; SqlConnection db_connection = new SqlConnection(prop.Connection_string); db_connection.Open(); file.WriteLine(DateTime.Now.ToString("g", ci) + " [+] Выбираем заказы на экспорт"); file.Flush(); SqlCommand db_command = new SqlCommand("SELECT [number], [auto_export], [id_place] FROM [order] WHERE [auto_export] > 0;", db_connection); SqlDataAdapter db_adapter = new SqlDataAdapter(db_command); DataTable tbl = new DataTable(); db_adapter.Fill(tbl); foreach (DataRow rw in tbl.Rows) { try { file.WriteLine(DateTime.Now.ToString("g", ci) + " [+] Подготавливаем к выгрузке заказ " + rw["number"].ToString().Trim()); file.Flush(); PSA.Lib.Util.ExportOrder.autoExport((int)rw["auto_export"], rw["number"].ToString().Trim()); db_command = new SqlCommand("SELECT [server], [path], [username], [password] FROM [place] WHERE [id_place] = " + rw["id_place"], db_connection); db_adapter = new SqlDataAdapter(db_command); DataTable ptbl = new DataTable(); db_adapter.Fill(ptbl); if (ptbl.Rows.Count > 0) { DataRow place = ptbl.Rows[0]; file.WriteLine(DateTime.Now.ToString("g", ci) + " [+] Выгружаем заказ " + rw["number"].ToString().Trim() + " на " + place["server"].ToString().Trim() + " в " + place["path"].ToString().Trim()); file.Flush(); using (FtpConnection connection = new FtpConnection( place["server"].ToString().Trim(), place["username"].ToString().Trim(), place["password"].ToString().Trim())) { connection.Encoding = Encoding.GetEncoding(1251); file.WriteLine("from: " + prop.Dir_export + "\\auto_export\\" + rw["number"].ToString().Trim() + "\\"); file.Flush(); DiskFolder source = new DiskFolder(prop.Dir_export + "\\auto_export\\" + rw["number"].ToString().Trim() + "\\"); string ftp_to = place["path"].ToString().Trim() + rw["number"].ToString().Trim() + "/"; if (ftp_to.Substring(0, 1) == "/") ftp_to = ftp_to.Substring(1); file.WriteLine("to: " + ftp_to); file.Flush(); try { FtpFolder _ftp_to = new FtpFolder(connection, ftp_to); _ftp_to.Delete(); } catch { } FtpFolder destination = new FtpFolder(connection, ftp_to); StreamWriter _tmp = new StreamWriter(prop.Dir_export + "\\auto_export\\" + rw["number"].ToString().Trim() + "\\.lock"); _tmp.Write("\n"); _tmp.Close(); db_command = new SqlCommand("UPDATE [order] SET [status_export] = 'Началась выгрузка', [status_export_date] = getdate() WHERE [number] = '" + rw["number"].ToString().Trim() + "'", db_connection); db_command.ExecuteNonQuery(); source.CopyFilesTo(destination, true, true); FtpFile _lock = new FtpFile(connection, ftp_to + ".lock"); _lock.Delete(); db_command = new SqlCommand("UPDATE [order] SET [auto_export] = -1, [status_export] = 'Отправлен', [status] = '500000', [status_export_date] = getdate() WHERE [number] = '" + rw["number"].ToString().Trim() + "'", db_connection); db_command.ExecuteNonQuery(); file.WriteLine(DateTime.Now.ToString("g", ci) + " [+] Выгружен заказ " + rw["number"].ToString().Trim()); file.Flush(); Directory.Delete(prop.Dir_export + "\\auto_export\\" + rw["number"].ToString().Trim() + "\\", true); } } } catch (Exception ex) { db_command = new SqlCommand("UPDATE [order] SET [status_export] = '" + ex.Message + "', [status_export_date] = getdate() WHERE [number] = '" + rw["number"].ToString().Trim() + "'", db_connection); db_command.ExecuteNonQuery(); file.WriteLine(DateTime.Now.ToString("g", ci) + " [!] Ошибка выгрузки заказа " + ex.Message + "\n" + ex.Source + "\n" + ex.StackTrace); file.Flush(); } } } catch (Exception ex) { file.WriteLine(DateTime.Now.ToString("g", ci) + " [!] Ошибка выгрузки заказов " + ex.Message + "\n" + ex.Source + "\n" + ex.StackTrace); file.Flush(); } finally { UploadWork = false; } } } catch (Exception ex) { file.WriteLine(DateTime.Now.ToString("g", ci) + " [!] Глобальная ошибка по время отправления " + ex.Message); file.Flush(); } }
public void DoAction() { string strProcedureName = string.Format( "{0}.{1}", className, MethodBase.GetCurrentMethod().Name); WriteLog.Instance.WriteBeginSplitter(strProcedureName); try { if (uploadType == "FTP") { WriteLog.Instance.Write(string.Format("向FTP[{0}]上传文件[{1}],文件内容:[{2}]", address, fileName, strData), strProcedureName); int port = 21; int.TryParse(strPort, out port); string FTPpath = string.Format(@"{0}{1}\", AppDomain.CurrentDomain.BaseDirectory, uploadfilePath); string fullFileName = FTPpath + fileName; string remotefile = string.Format(@"{0}\{1}", uploadfilePath, fileName); using (FtpConnection ftp = new FtpConnection(address, port, userID, pwd)) { try { ftp.Open(); ftp.Login(); if (!Directory.Exists(FTPpath)) { Directory.CreateDirectory(FTPpath); } if (!System.IO.File.Exists(fullFileName)) { System.IO.FileStream fs = System.IO.File.Create(fullFileName); System.IO.StreamWriter sw = new System.IO.StreamWriter(fs, Encoding.Default);//ANSI编码格式 sw.Write(strData); sw.Flush(); sw.Close(); fs.Close(); } ftp.PutFile(fullFileName, remotefile); WriteLog.Instance.Write("文件上传成功!", strProcedureName); ftp.Close(); } catch (Exception error) { WriteLog.Instance.Write(error.Message, strProcedureName); XtraMessageBox.Show( error.Message, "系统信息", MessageBoxButtons.OK, MessageBoxIcon.Error); } finally { if (System.IO.File.Exists(fullFileName)) { System.IO.File.Delete(fullFileName); } } } } else if (uploadType == "HTTP") { } else if (uploadType == "ShareFolder") { } } finally { WriteLog.Instance.WriteEndSplitter(strProcedureName); } }
/// <summary> /// Initializes a new instance of the <see cref="XmkdCommandHandler"/> class. /// </summary> /// <param name="connection">The connection to create this command handler for</param> public XmkdCommandHandler(FtpConnection connection) : base(connection, "XMKD") { }
/// <summary> /// Initializes a new instance of the <see cref="RetrCommandHandler"/> class. /// </summary> /// <param name="connection">The connection to create this command handler for</param> public RetrCommandHandler(FtpConnection connection) : base(connection, "RETR") { }
public void PublishToGitFTP(DeploymentModel model) { if (model.GitDeployment) { Logger.Debug("Executing git add"); var addProcess = new Process(); var addProcessStartInfo = new ProcessStartInfo("\"" + gitLocation + "\"") { RedirectStandardOutput = true, RedirectStandardError = true, UseShellExecute = false, Arguments = " --git-dir=\"" + fullPublishGitPath + "\" --work-tree=\"" + publishGitPath + "\" add -A" }; addProcess.StartInfo = addProcessStartInfo; addProcess.OutputDataReceived += (sender, args) => Logger.Debug(args.Data); addProcess.ErrorDataReceived += (sender, args) => Logger.Debug(args.Data); addProcess.Start(); addProcess.BeginOutputReadLine(); addProcess.BeginErrorReadLine(); addProcess.WaitForExit(); Logger.Debug("git add process to exited"); Logger.Debug("Executing git email config process"); var emailProcess = new Process(); var emailProcessStartInfo = new ProcessStartInfo("\"" + gitLocation + "\"") { RedirectStandardOutput = true, RedirectStandardError = true, UseShellExecute = false, Arguments = " --git-dir=\"" + fullPublishGitPath + "\" --work-tree=\"" + publishGitPath + "\" config user.email \"[email protected]\"" }; emailProcess.StartInfo = emailProcessStartInfo; emailProcess.OutputDataReceived += (sender, args) => Logger.Debug(args.Data); emailProcess.ErrorDataReceived += (sender, args) => Logger.Debug(args.Data); emailProcess.Start(); emailProcess.BeginOutputReadLine(); emailProcess.BeginErrorReadLine(); emailProcess.WaitForExit(); Logger.Debug("git email config process to exited"); Logger.Debug("Executing git name config process"); var userProcess = new Process(); var userProcessStartInfo = new ProcessStartInfo("\"" + gitLocation + "\"") { RedirectStandardOutput = true, RedirectStandardError = true, UseShellExecute = false, Arguments = " --git-dir=\"" + fullPublishGitPath + "\" --work-tree=\"" + publishGitPath + "\" config user.name \"barbato\"" }; userProcess.StartInfo = userProcessStartInfo; userProcess.OutputDataReceived += (sender, args) => Logger.Debug(args.Data); userProcess.ErrorDataReceived += (sender, args) => Logger.Debug(args.Data); userProcess.Start(); userProcess.BeginOutputReadLine(); userProcess.BeginErrorReadLine(); userProcess.WaitForExit(); Logger.Debug("git name config process to exited"); Logger.Debug("Executing git commit"); var commitProcess = new Process(); var commitProcessStartInfo = new ProcessStartInfo("\"" + gitLocation + "\"") { RedirectStandardOutput = true, RedirectStandardError = true, UseShellExecute = false, Arguments = " --git-dir=\"" + fullPublishGitPath + "\" --work-tree=\"" + publishGitPath + "\" commit -a -m \"Static Content Regenerated\"" }; commitProcess.StartInfo = commitProcessStartInfo; commitProcess.OutputDataReceived += (sender, args) => Logger.Debug(args.Data); commitProcess.ErrorDataReceived += (sender, args) => Logger.Debug(args.Data); commitProcess.Start(); commitProcess.BeginOutputReadLine(); commitProcess.BeginErrorReadLine(); commitProcess.WaitForExit(); Logger.Debug("git commit process to exited"); Logger.Debug("Executing git push"); var pushProcess = new Process(); var pushProcessStartInfo = new ProcessStartInfo("\"" + gitLocation + "\"") { RedirectStandardOutput = true, RedirectStandardError = true, UseShellExecute = false, Arguments = " --git-dir=\"" + fullPublishGitPath + "\" push -f origin master" }; pushProcess.OutputDataReceived += (sender, args) => Logger.Debug(args.Data); pushProcess.ErrorDataReceived += (sender, args) => Logger.Debug(args.Data); pushProcess.StartInfo = pushProcessStartInfo; pushProcess.Start(); pushProcess.BeginOutputReadLine(); pushProcess.BeginErrorReadLine(); pushProcess.WaitForExit(); Logger.Debug("git push process to exited"); } else { using (ftp = new FtpConnection(model.FTPServer, model.FTPUsername, model.FTPPassword)) { try { ftp.Open(); ftp.Login(); if (!string.IsNullOrWhiteSpace(model.FTPPath)) { var parrentDirectory = String.Format("/{0}", Path.GetDirectoryName(model.FTPPath).Replace(Path.DirectorySeparatorChar, '/')); /* Get name of the directory */ var checkingDirectory = String.Format("{0}", Path.GetFileName(model.FTPPath)).ToLower(); /* Get all child directories info of the parent directory */ var ftpDirectories = ftp.GetDirectories(parrentDirectory); /* check if the given directory exists in the returned result */ var exists = ftpDirectories.Any(d => d.Name.ToLower() == checkingDirectory); if (!exists) { ftp.CreateDirectory(model.FTPPath); } ftp.SetCurrentDirectory(model.FTPPath); } FtpBlogFiles(publishGitPath, model.FTPPath); } catch (Exception ex) { } } } }
/// <summary> /// Initializes a new instance of the <see cref="StorCommandHandler"/> class. /// </summary> /// <param name="connection">The connection this command handler is created for</param> public StorCommandHandler(FtpConnection connection) : base(connection, "STOR") { }
/// <summary> /// Initializes a new instance of the <see cref="RntoCommandHandler"/> class. /// </summary> /// <param name="connection">The connection to create this command handler for</param> public RntoCommandHandler(FtpConnection connection) : base(connection, "RNTO") { }
/// <summary> /// Initializes a new instance of the <see cref="FtpCommandHandlerExtension"/> class. /// </summary> /// <param name="connection">The connection this instance is used for</param> /// <param name="extensionFor">The name of the command this extension is for</param> /// <param name="name">The command name</param> /// <param name="alternativeNames">Alternative names</param> protected FtpCommandHandlerExtension([NotNull] FtpConnection connection, [NotNull] string extensionFor, [NotNull] string name, [NotNull, ItemNotNull] params string[] alternativeNames) : base(connection, name, alternativeNames) { ExtensionFor = extensionFor; }
/// <summary> /// Initializes a new instance of the <see cref="FtpCommandHandler"/> class. /// </summary> /// <param name="connection">The connection this instance is used for</param> /// <param name="name">The command name</param> /// <param name="alternativeNames">Alternative names</param> protected FtpCommandHandler([NotNull] FtpConnection connection, [NotNull] string name, [NotNull, ItemNotNull] params string[] alternativeNames) : base(connection, name, alternativeNames) { }
/// <summary> /// Initializes a new instance of the <see cref="HelpCommandHandler"/> class. /// </summary> /// <param name="connection">The connection to create this command handler for</param> public HelpCommandHandler(FtpConnection connection) : base(connection, "HELP") { }
/// <summary> /// Initializes a new instance of the <see cref="AborCommandHandler"/> class. /// </summary> /// <param name="connection">The connection to create this command handler for</param> public AborCommandHandler(FtpConnection connection) : base(connection, "ABOR") { }
/// <summary> /// Initializes a new instance of the <see cref="PbszCommandHandler"/> class. /// </summary> /// <param name="connection">The connection to create this command handler for</param> public PbszCommandHandler(FtpConnection connection) : base(connection, "PBSZ") { }
/// <summary> /// Initializes a new instance of the <see cref="SizeCommandHandler"/> class. /// </summary> /// <param name="connection">The connection to create this command handler for</param> public SizeCommandHandler(FtpConnection connection) : base(connection, "SIZE") { }
/// <summary> /// Initializes a new instance of the <see cref="ListCommandHandler"/> class. /// </summary> /// <param name="connection">The connection to create this command handler for</param> public ListCommandHandler(FtpConnection connection) : base(connection, "LIST", "NLST", "LS") { }
/// <summary> /// Initializes a new instance of the <see cref="OptsCommandHandler"/> class. /// </summary> /// <param name="connection">The connection to create this command handler for</param> public OptsCommandHandler(FtpConnection connection) : base(connection, "OPTS") { Extensions = new Dictionary<string, FtpCommandHandlerExtension>(StringComparer.OrdinalIgnoreCase); }
/// <summary> /// Initializes a new instance of the <see cref="RnfrCommandHandler"/> class. /// </summary> /// <param name="connection">The connection to create this command handler for</param> public RnfrCommandHandler(FtpConnection connection) : base(connection, "RNFR") { }
/// <summary> /// Initializes a new instance of the <see cref="OptsCommandHandler"/> class. /// </summary> /// <param name="connection">The connection to create this command handler for</param> public OptsCommandHandler(FtpConnection connection) : base(connection, "OPTS") { Extensions = new Dictionary <string, FtpCommandHandlerExtension>(StringComparer.OrdinalIgnoreCase); }
/// <summary> /// Initializes a new instance of the <see cref="QuitCommandHandler"/> class. /// </summary> /// <param name="connection">The connection to create this command handler for</param> public QuitCommandHandler(FtpConnection connection) : base(connection, "QUIT", "LOGOUT") { }
/// <summary> /// ����Ftp /// </summary> /// <returns></returns> private FtpConnection FtpConn() { ftp=new FtpConnection(); ftp.Connect(this.FtpIP,this.FtpUserName,this.FtpPassord); return ftp; }
/// <summary> /// Initializes a new instance of the <see cref="RestCommandHandler"/> class. /// </summary> /// <param name="connection">The connection to create this command handler for</param> public RestCommandHandler(FtpConnection connection) : base(connection, "REST") { }
/// <summary> /// Initializes a new instance of the <see cref="PasvCommandHandler"/> class. /// </summary> /// <param name="connection">The connection this command handler is created for</param> public PasvCommandHandler(FtpConnection connection) : base(connection, "PASV", "EPSV") { }
/// <summary> /// Initializes a new instance of the <see cref="PassCommandHandler"/> class. /// </summary> /// <param name="connection">The connection to create this command handler for</param> public PassCommandHandler(FtpConnection connection) : base(connection, "PASS") { }
internal FtpRenameCommand(FtpConnection connection, FtpPath source, FtpPath target) : base(connection, source) { Target = target; }
/// <summary> /// Initializes a new instance of the <see cref="DeleCommandHandler"/> class. /// </summary> /// <param name="connection">The connection to create this command handler for</param> public DeleCommandHandler(FtpConnection connection) : base(connection, "DELE") { }
/// <summary> /// Initializes a new instance of the <see cref="TypeCommandHandler"/> class. /// </summary> /// <param name="connection">The connection to create this command handler for</param> public TypeCommandHandler(FtpConnection connection) : base(connection, "TYPE") { }
/// <summary> /// Initializes a new instance of the <see cref="UserCommandHandler"/> class. /// </summary> /// <param name="connection">The connection to create this command handler for</param> public UserCommandHandler(FtpConnection connection) : base(connection, "USER") { }
internal FtpTransportStream(FtpConnection connection) : base(connection, null) { }
/// <summary> /// Initializes a new instance of the <see cref="StruCommandHandler"/> class. /// </summary> /// <param name="connection">The connection to create this command handler for</param> public StruCommandHandler(FtpConnection connection) : base(connection, "STRU") { }
/// <summary> /// Initializes a new instance of the <see cref="CwdCommandHandler"/> class. /// </summary> /// <param name="connection">The connection to create this command handler for</param> public CwdCommandHandler(FtpConnection connection) : base(connection, "CWD") { }
/// <summary> /// Initializes a new instance of the <see cref="RmdCommandHandler"/> class. /// </summary> /// <param name="connection">The connection to create this command handler for</param> public RmdCommandHandler(FtpConnection connection) : base(connection, "RMD") { }
/// <summary> /// Initializes a new instance of the <see cref="ProtCommandHandler"/> class. /// </summary> /// <param name="connection">The connection to create this command handler for</param> public ProtCommandHandler(FtpConnection connection) : base(connection, "PROT") { }
/// <summary> /// Initializes a new instance of the <see cref="MdtmCommandHandler"/> class. /// </summary> /// <param name="connection">The connection to create this command handler for</param> public MdtmCommandHandler(FtpConnection connection) : base(connection, "MDTM") { }
/// <summary> /// Initializes a new instance of the <see cref="AuthTlsCommandHandler"/> class. /// </summary> /// <param name="connection">The connection this instance is used for</param> public AuthTlsCommandHandler(FtpConnection connection) : base(connection, "AUTH") { }
/// <summary> /// Initializes a new instance of the <see cref="AlloCommandHandler"/> class. /// </summary> /// <param name="connection">The connection to create this command handler for</param> public AlloCommandHandler(FtpConnection connection) : base(connection, "ALLO") { }
/// <summary> /// Initializes a new instance of the <see cref="NoOpCommandHandler"/> class. /// </summary> /// <param name="connection">The connection to create this command handler for</param> public NoOpCommandHandler(FtpConnection connection) : base(connection, "NOOP") { }