private void Form1_Load(object sender, EventArgs e) { FtpClient conn = new FtpClient(); conn.Host = "ftp://" + "192.168.1.12"; conn.AutoConnect(); }
private void UploadAll() { if (Program.YamlData.FTPs != null) { foreach (FTP ftp in Program.YamlData.FTPs) { Console.WriteLine($"Uploading to {ftp.Server} ..."); NetworkCredential creds = new NetworkCredential(ftp.User, ftp.Password); using (FtpClient ftpClient = new FtpClient(ftp.Server, ftp.Port, creds)) { FtpProfile ftpProf = ftpClient.AutoConnect(); if (ftpProf == null) { throw new Error($"Can't connect to FTP server {ftp.Server}"); } foreach (FTPCopy copy in Program.YamlData.FTPCopy) { string from = Path.Combine(Program.YamlData.Deploy.BaseFolder, copy.From); Upload(ftpClient, from, copy.To, ReplaceBG: copy.ReplaceBG, Conditional: copy.Conditional); } } } } }
public DemoBackuper(ILogger <DemoBackuper> logger) { myLogger = logger; var ftpCredentials = new NetworkCredential(Settings.DemoBackupFTPUsername, Settings.DemoBackupFTPPassword); myFtpClient = new FtpClient(Settings.DemoBackupFTP, 1818, ftpCredentials); myFtpClient.AutoConnect(); }
private void Form1_Load(object sender, EventArgs e) { FtpClient conn = new FtpClient(); conn.Host = "ftp://" + "192.168.1.12"; conn.AutoConnect(); MessageBox.Show("切换账号修改测试"); }
public void TestAutoConnect() { using (FtpClient cl = NewFtpClient_Tele2SpeedTest()) { var profile = cl.AutoConnect(); if (profile != null) { var code = profile.ToCode(); } } }
public override void Init() { Client = new FtpClient((string)PatchMod.Config["FTPHost"], (int)PatchMod.Config["FTPPort", typeof(int)], new NetworkCredential((string)PatchMod.Config["FTPUsername"], (string)PatchMod.Config["FTPPassword"])); if (Client.AutoConnect() != null) { LogClient.LogMessage($"FTP Connected."); } else { LogClient.LogMessage($"Unable to connect to remote host via FTP."); } }
/// <summary> /// Helper to test the connection /// </summary> public void TestConnection() { try { Error = ""; Information = ""; if (Protocol == FileServerProtocol.FTP) { FtpClient client = new FtpClient(HostName, UserName, ClearPassword); if (PortNumber == 0) { client.AutoConnect(); } else { client.Port = PortNumber; client.Connect(); } client.Disconnect(); } else if (Protocol == FileServerProtocol.SFTP) { using (var sftp = new SftpClient(HostName, UserName, ClearPassword)) { sftp.Connect(); sftp.Disconnect(); } } else if (Protocol == FileServerProtocol.SCP) { using (var scp = new ScpClient(HostName, UserName, ClearPassword)) { scp.Connect(); scp.Disconnect(); } } Information = string.Format("The connection to '{0}:{1}' is successfull", HostName, PortNumber); } catch (Exception ex) { Error = ex.Message; if (ex.InnerException != null) { Error += " " + ex.InnerException.Message.Trim(); } Information = "Error got testing the connection."; } }
protected async Task <Task> FtpFileUpload(string fileName, DiscordMember member) { ftpClient.AutoConnect(); string fileNameLower = fileName.ToLower(); await DownloadImageAsync("ProfilePics/", fileNameLower, new Uri(member.GetAvatarUrl(ImageFormat.Jpeg, 2048))); await DownloadImageAsync("ProfilePics/", fileNameLower, new Uri(member.GetAvatarUrl(ImageFormat.WebP, 2048))); await ftpClient.UploadFileAsync($"ProfilePics/{fileNameLower}.jpg", $"/sweatyvirgins.com/htdocs/assets/Images/Profiles/{fileName}/{fileNameLower}.jpg/", FtpRemoteExists.Overwrite, true); await ftpClient.UploadFileAsync($"ProfilePics/{fileNameLower}.webp", $"/sweatyvirgins.com/htdocs/assets/Images/Profiles/{fileName}/{fileNameLower}.webp/", FtpRemoteExists.Overwrite, true); ftpClient.AutoDispose(); return(Task.CompletedTask); }
public void BackupDemoFile(Demo demo, bool deleteFileAfterUpload) { var filePath = demo.FilePath; myLogger.LogInformation($"Trying to back up demo file ({filePath})"); if (!System.IO.File.Exists(filePath)) { myLogger.LogWarning($"The file to be backed up does not exist: {filePath}"); throw new Exception($"The file to be backed up does not exist: {filePath}"); } if (!myFtpClient.IsConnected) { myFtpClient.AutoConnect(); } var remoteDemoFileName = demo.State == DemoState.ParseFailure ? $"{demo.Id}_parseFailure.dem" : $"{demo.Id}.dem"; var remoteFilePath = $"/csgo/{remoteDemoFileName}"; var uploadResultStatus = myFtpClient.UploadFile(filePath, remoteFilePath, FtpRemoteExists.Skip, false, FtpVerify.Retry); if (uploadResultStatus == FtpStatus.Failed) { myLogger.LogWarning($"Uploading the demo file ({remoteDemoFileName}) to the FTP failed."); throw new Exception($"Uploading the demo file ({remoteDemoFileName}) to the FTP failed."); } myLogger.LogInformation($"Successfully backed up demo file {remoteDemoFileName}"); if (deleteFileAfterUpload) { myLogger.LogInformation($"Deleting backed up demo file {remoteDemoFileName}"); System.IO.File.Delete(filePath); } }
public virtual FileInfo DownloadFile(string url, string filename) { if (string.IsNullOrWhiteSpace(url)) { throw new ArgumentNullException(nameof(url)); } if (string.IsNullOrWhiteSpace(RequestEmail) || !RequestEmail.Contains('@') || RequestEmail.Length < 10) { Log.WriteLine("Internal error. Cannot request FTP content because no contact email is provided.", LogLevel.Error); throw new InvalidOperationException("No valid requesting contact email provided. Please set the RequestEmail to continue. Cant comply."); } FileInfo localFile = new FileInfo(Path.Combine(CacheDirectory, filename)); if (!localFile.Directory.Exists) { localFile.Directory.Create(); } if (OfflineMode) { localFile.Refresh(); if (!localFile.Exists) { throw new FileNotFoundException("The downloaded file cannot be located. Application is in offline mode."); } Log.WriteLine("Offline mode. No file download for %@. Cached file size: %@ bytes", LogLevel.Message, localFile.Name, localFile.Length.ToString("N0")); return(localFile); } if (FtpClient == null) { FtpClient = new FluentFTP.FtpClient(PublicFtpHostname, PublicFtpPort, new System.Net.NetworkCredential("anonymous", RequestEmail)); FtpClient.ConnectTimeout = 7000; FtpClient.DataConnectionConnectTimeout = 7000; FtpClient.DataConnectionReadTimeout = 10000; FtpClient.ReadTimeout = 7000; } else { Log.WriteLine("Reusing existing FTP connection to ftp://%@@%@:%@", LogLevel.Debug, FtpClient.Credentials.UserName, PublicFtpHostname, PublicFtpPort.ToString()); } int tryIndex = 0; int maxTries = 10; int tryDelayFormulaBase = 2; bool abortLoop = false; while (!FtpClient.IsConnected) { try { if (tryIndex >= maxTries) { abortLoop = true; throw new IOException("Cannot connect to the remote server."); } int delay = tryIndex > 0 ? (int)Math.Pow(tryDelayFormulaBase, tryIndex) : 0; if (delay > 0) { if (Settings.Current.HeadlessMode) { Log.Write("Retrying in %@ seconds... ", LogLevel.Message, delay.ToString("N0")); System.Threading.Thread.Sleep(delay * 1000); } else { Log.Write("Retrying in %@ seconds. Press Q at any time to abort. ", LogLevel.Message, delay.ToString("N0")); for (int i = 0; i < delay; i++) { System.Threading.Thread.Sleep(1000); while (Console.KeyAvailable) { if (Console.ReadKey().Key == ConsoleKey.Q) { abortLoop = true; throw new TimeoutException("The operation timed out and a retry attempt was aborted"); } } } } Log.WriteLine("Retrying..."); } if (tryIndex > 0) { Log.Write("Try %@ of %@. ", LogLevel.Message, tryIndex + 1, maxTries); } tryIndex++; Log.Write("Connecting to the remote FTP host (%@) at ftp://%@@%@:%@... ", LogLevel.Message, Identifier, FtpClient.Credentials.UserName, PublicFtpHostname, PublicFtpPort.ToString()); FtpClient.RetryAttempts = 1; FluentFTP.FtpProfile profile = FtpClient.AutoConnect(); if (profile == null || !FtpClient.IsConnected) { throw new TimeoutException("The operation timed out."); } Log.WriteColoredLine("OK! (%@)", ConsoleColor.Green, LogLevel.Message, profile.DataConnection.ToString()); } catch (Exception ex) { Log.WriteColoredLine("FAIL!", ConsoleColor.Red, LogLevel.Error); Log.WriteLine("Failed to connect. %@. %@", LogLevel.Error, ex.GetType().Name, ex.Message); if (abortLoop) { throw; } } } Log.WriteLine("Connected to ftp://%@@%@:%@/. Server Type: %@", LogLevel.Debug, FtpClient.Credentials.UserName, PublicFtpHostname, PublicFtpPort.ToString(), FtpClient.SystemType); Log.WriteLine("Requesting file info for %@...", LogLevel.Debug, url); try { FluentFTP.FtpListItem remoteFileInfo = FtpClient.GetObjectInfo(url); if (remoteFileInfo == null) { throw new IOException("The requested FTP file does not exists."); } FtpCurrentTransferSize = FtpClient.GetFileSize(url); Log.WriteLine(" File size: %@ bytes.", LogLevel.Debug, FtpCurrentTransferSize.ToString("N0")); if (FtpCurrentTransferSize == 0) { //FtpClient.Disconnect(); throw new IOException("The requested file is empty."); } } catch (Exception ex) { Log.WriteLine("An error occurred while requesting file info. %@. %@", LogLevel.Warning, ex.GetType().Name, ex.Message); throw; } try { using (FileStream fs = new FileStream(localFile.FullName, FileMode.Create, FileAccess.Write, FileShare.None)) { FtpClient.Download(fs, url, progress: FtpTransferProgressUpdated); if (Console.CursorLeft > 0) { Log.WriteLine(); } if (fs.Position == FtpCurrentTransferSize || FtpCurrentTransferSize == -1) { Log.WriteLine("File transfer completed. %@ bytes received.", LogLevel.Debug, fs.Position.ToString("N0")); } else { Log.WriteLine("File transfer completed but file size differs!!. Expected %@ but received %@ bytes.", LogLevel.Error, FtpCurrentTransferSize.ToString("N0"), fs.Position.ToString("N0")); if (!Settings.Current.IgnoreFtpTransferSizeMismatch) { //FtpClient.Disconnect(); throw new IOException("The received file doesnt match the expected file length."); } } } } catch (Exception ex) { Log.WriteLine("An error occurred while requesting the file. %@. %@. Aborted.", LogLevel.Error, ex.GetType().Name, ex.Message); throw; } //FtpClient.Disconnect(); //Log.WriteLine("Disconnected from FTP server.", LogLevel.Debug); localFile.Refresh(); return(localFile); }