/// <summary> /// /// </summary> /// <param name="fileName"></param> /// <param name="dir"></param> public void upload(string fileName, string remoteFile) { logger.pushOperation("FTP.upload"); try { string dir = remoteFile.Substring(0, remoteFile.LastIndexOf("/") + 1); if (File.Exists(fileName)) { try { sFTP.SetCurrentDirectory(dir); } catch (Exception e) { logger.log("Erro: " + e.Message, Logger.LogType.ERROR, e, false); } sFTP.PutFile(fileName, remoteFile); } else { logger.log(string.Format("Arquivo {0} inexistente.", fileName), Logger.LogType.WARNING); } } catch (Exception e) { logger.log("Erro ao conectar FTP: " + e.Message, Logger.LogType.ERROR, e, false); } finally { logger.releaseOperation(); } }
static void Main(string[] args) { try { string strSource = "D:\\Syed\\" + "Sample.txt"; string ftpusername = "******"; string ftppassword = "******"; string ip = "172.26.50.199";//provide ur ftp server ip address int FtpPort = Convert.ToInt16(21); string RemoteFileName = "Notifications\\sample.txt"; using (FtpConnection _ftp = new FtpConnection(ip, FtpPort, ftpusername, ftppassword)) { try { string str = Path.GetFullPath("D:\\Syed\\sample.txt"); _ftp.Open(); _ftp.Login(); _ftp.PutFile(strSource, RemoteFileName); } catch (FtpException ex) { throw ex; } } Program obj = new Program(); obj.GetFile(); } catch (System.Exception ex) { throw ex; } }
private void buttonPublishBulletin_Click(object sender, EventArgs e) { var source = openFileDialog2.FileName; var fileName = openFileDialog2.SafeFileName; var destinationFileName = txtCaption.Text == String.Empty ? fileName : txtCaption.Text.Replace(" ", "_") + fileName.Substring(fileName.LastIndexOf(".")); var destinationFolder = getBulletinsPagePath(); var destination = String.Format("{0}/{1}", destinationFolder, destinationFileName); using (var ftp = new FtpConnection(m_ftpSite, m_ftpUsername, m_ftpPassword)) { try { ftp.Open(); ftp.Login(); if (!ftp.DirectoryExists(destinationFolder)) { MessageBox.Show( "The destination folder doesn't exist on the server. Please contact the BFI website administrator."); } ftp.PutFile(source, destination); MessageBox.Show("Published bulletin successfully"); } catch (Exception ex) { MessageBox.Show(ex.Message); } } }
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); }
void sendCommentClick(object sender, EventArgs e) { try { string localPath = Path.GetTempPath() + "mecomment.dat"; File.WriteAllText(localPath, "\n\n\n\n\n\n\n\n\n\n\n\n" + this.commentBox.Text); ftp.SetCurrentDirectory("/dev_hdd0/home/" + allusers[accLists.SelectedIndex] + "/friendim/"); ftp.PutFile(localPath); MetroMessageBox.Show(this, "Successfully loaded", "Success", MessageBoxButtons.OK, MessageBoxIcon.Asterisk); } catch { MetroMessageBox.Show(this, "Error couldn't find the folder", "Success", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
private void BtnUploadClick(object sender, EventArgs e) { using (var uploadFile = new OpenFileDialog { Multiselect = false, InitialDirectory = _directoryUpload }) { if (uploadFile.ShowDialog() == DialogResult.OK) { _ftp.PutFile(uploadFile.FileName); } } }
/// <summary> /// 上传文件 /// </summary> public virtual void UpLoadFile(string sFileName, string remotePath) { try { FileInfo fileInf = new FileInfo(sFileName); var remoteFile = Combine(remotePath, fileInf.Name); if (ftpConnection.FileExists(remoteFile)) { Delete(remoteFile); } ftpConnection.PutFile(sFileName, remoteFile); } catch { throw; } }
// Function to store ftp public bool s2FTP(String url, String name) { using (FtpConnection ftp = new FtpConnection("127.0.0.1", "rahul", "rahul")) {; /* Open the FTP connection */ ftp.Open(); /* Login using previously provided credentials */ ftp.Login(); try { ftp.SetCurrentDirectory("/"); ftp.PutFile(@url, name); /* 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)); } } return(true); }
public void StartFTP() { string msg = string.Empty; if (dataBase_.dtSettlePrice.Rows.Count > 0) { if (File.Exists(ftpFileName_)) { File.Delete(ftpFileName_); } using (FtpConnection ftp = new FtpConnection(ftpIP_, ftpID_, ftpPassword_)) { using (StreamWriter streamWriter = new StreamWriter(ftpFileName_, false)) { foreach (DataRow item in dataBase_.dtSettlePrice.Rows) { streamWriter.WriteLine(string.Format("{0,-16}{1,-6} {2:000000.000000} ", item["Pid"], item["YM"], item["SettlePrice"])); } streamWriter.Flush(); } ftp.Open(); ftp.Login(); try { ftp.SetCurrentDirectory(ftpDirectory_); ftp.PutFile(ftpFileName_, ftpFileName_); msg = string.Format("{0}\t{1}:{2},Finish FTP Closing to {3}", DateTime.Now.ToString("hh:mm:ss.ffff"), MethodBase.GetCurrentMethod().ReflectedType.Name, MethodBase.GetCurrentMethod().Name, ftpIP_); srnItems_.lbLogs.InvokeIfNeeded(() => srnItems_.lbLogs.Items.Insert(0, msg)); } catch (FtpException ex) { msg = String.Format("{0}\t{1}:{2}, Exception ErrCode: {3}, Message: {4}", DateTime.Now.ToString("hh:mm:ss.ffff"), MethodBase.GetCurrentMethod().ReflectedType.Name, MethodBase.GetCurrentMethod().Name, ex.ErrorCode, ex.Message); srnItems_.lbLogs.InvokeIfNeeded(() => srnItems_.lbLogs.Items.Insert(0, msg)); } } } else { msg = string.Format("{0}\t{1}:{2},本日無資料 !", DateTime.Now.ToString("hh:mm:ss.ffff"), MethodBase.GetCurrentMethod().ReflectedType.Name, MethodBase.GetCurrentMethod().Name, ftpIP_); srnItems_.lbLogs.InvokeIfNeeded(() => srnItems_.lbLogs.Items.Insert(0, msg)); } }
static void Main(string[] args) { string error = ""; try { error = "host error"; string host = args[0]; error = "localPath error"; string localFilePath = args[1]; error = "serverPath error"; string serverFilePath = args[2]; error = "error connecting.."; using (FtpConnection ftp = new FtpConnection(host)) { if (!ftp.IsConnected) { Console.WriteLine(error); } error = "error moving file..!"; string fileName = serverFilePath.Contains("/") ? serverFilePath.Substring(serverFilePath.LastIndexOf('/')).Replace("/", "").Replace("//", "") : serverFilePath; string dirPath = serverFilePath.Contains("/") ? serverFilePath.Substring(0, serverFilePath.LastIndexOf('/')) + '/' : "dev_hdd0/"; ftp.SetCurrentDirectory(dirPath); ftp.PutFile(localFilePath, fileName); foreach (var item in ftp.GetFiles()) { if (item.FullName == fileName) { Console.WriteLine("success :\nsource( {0} )\ndestination( {1} )", localFilePath, dirPath + fileName); MessageBeep(0); break; } } } } catch { Console.WriteLine(error); MessageBeep(16); Console.Read(); } }
/// <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)); } } } }
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()
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 FtpBlogFiles(string dirPath, string uploadPath) { string[] files = Directory.GetFiles(dirPath, "*.*"); string[] subDirs = Directory.GetDirectories(dirPath); foreach (string file in files) { ftp.PutFile(file, Path.GetFileName(file)); } foreach (string subDir in subDirs) { if (!ftp.DirectoryExists(uploadPath + "/" + Path.GetFileName(subDir))) { ftp.CreateDirectory(uploadPath + "/" + Path.GetFileName(subDir)); } ftp.SetCurrentDirectory(uploadPath + "/" + Path.GetFileName(subDir)); FtpBlogFiles(subDir, uploadPath + "/" + Path.GetFileName(subDir)); } }
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 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); } } } }
/// <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); } var overwrite = true; var files = new List <FtpFileInfo>(); if (!string.IsNullOrEmpty(this.Overwrite)) { if (!bool.TryParse(this.Overwrite, out overwrite)) { overwrite = true; } } if (!overwrite) { files.AddRange(ftpConnection.GetFiles()); } foreach (string fileName in this.FileNames.Select(item => item.ItemSpec)) { try { if (File.Exists(fileName)) { if (!overwrite && files.FirstOrDefault(fi => fi.Name == fileName) != null) { this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Skipped: {0}", fileName)); continue; } 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)); } } } }
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); } }
public void PutFile(string localFile, string remoteFile) { _ftpConnection.PutFile(localFile, remoteFile); }
private ActionResult FtpUpload(IJob job) { var actionResult = Check(job.Profile); if (!actionResult) { Logger.Error("Canceled FTP upload action."); return(actionResult); } if (string.IsNullOrEmpty(job.Passwords.FtpPassword)) { Logger.Error("No ftp password specified in action"); return(new ActionResult(ActionId, 102)); } Logger.Debug("Creating ftp connection.\r\nServer: " + job.Profile.Ftp.Server + "\r\nUsername: "******"Can not connect to the internet for login to ftp. Win32Exception Message:\r\n" + ex.Message); ftp.Close(); return(new ActionResult(ActionId, 108)); } Logger.Error("Win32Exception while login to ftp server:\r\n" + ex.Message); ftp.Close(); return(new ActionResult(ActionId, 104)); } catch (Exception ex) { Logger.Error("Exception while login to ftp server:\r\n" + ex.Message); ftp.Close(); return(new ActionResult(ActionId, 104)); } var fullDirectory = job.TokenReplacer.ReplaceTokens(job.Profile.Ftp.Directory).Trim(); if (!IsValidPath(fullDirectory)) { Logger.Warn("Directory contains invalid characters \"" + fullDirectory + "\""); fullDirectory = MakeValidPath(fullDirectory); } Logger.Debug("Directory on ftp server: " + fullDirectory); var directories = fullDirectory.Split(new[] { "/" }, StringSplitOptions.RemoveEmptyEntries); try { foreach (var directory in directories) { if (!ftp.DirectoryExists(directory)) { Logger.Debug("Create folder: " + directory); ftp.CreateDirectory(directory); } Logger.Debug("Move to: " + directory); ftp.SetCurrentDirectory(directory); } } catch (Exception ex) { Logger.Error("Exception while setting directory on ftp server\r\n:" + ex.Message); ftp.Close(); return(new ActionResult(ActionId, 105)); } var addendum = ""; if (job.Profile.Ftp.EnsureUniqueFilenames) { Logger.Debug("Generate addendum for unique filename"); try { addendum = AddendumForUniqueFilename(Path.GetFileName(job.OutputFiles[0]), ftp); Logger.Debug("The addendum for unique filename is \"" + addendum + "\" If empty, the file was already unique."); } catch (Exception ex) { Logger.Error("Exception while generating unique filename\r\n:" + ex.Message); ftp.Close(); return(new ActionResult(ActionId, 106)); } } foreach (var file in job.OutputFiles) { try { var targetFile = Path.GetFileNameWithoutExtension(file) + addendum + Path.GetExtension(file); ftp.PutFile(file, MakeValidPath(targetFile)); } catch (Exception ex) { Logger.Error("Exception while uploading the file \"" + file + "\": \r\n" + ex.Message); ftp.Close(); return(new ActionResult(ActionId, 107)); } } ftp.Close(); return(new ActionResult()); }