/// <summary> /// 서버 루트 디렉토리 탐색 재귀 함수 /// </summary> /// <param name="session"></param> /// <param name="Path"></param> /// <returns></returns> private TreeNode ServerRecuresiveDirectory(Session session, string Path, string FileName) { TreeNode rtnValue = new TreeNode { Text = FileName, Tag = Path }; RemoteDirectoryInfo directory = session.ListDirectory(Path); foreach (RemoteFileInfo fileInfo in directory.Files) { if (fileInfo.Name.Equals(".") || fileInfo.Name.Equals("..")) { continue; } if (fileInfo.IsDirectory) { rtnValue.Nodes.Add(ServerRecuresiveDirectory(session, string.Format("{0}/{1}", Path, fileInfo.Name), fileInfo.Name)); } else { rtnValue.Nodes.Add(new TreeNode { Text = fileInfo.Name, Tag = fileInfo.FullName }); } } return(rtnValue); }
/// <summary> /// Elimina un archivo del FTP /// </summary> /// <param name="nombreCv">nombre del archivo</param> /// <returns></returns> public bool deleteFtpFile(string nombreCv) { if (System.IO.File.Exists(ConfigurationManager.AppSettings["pathCv"] + nombreCv)) { File.Delete(ConfigurationManager.AppSettings["pathCv"] + nombreCv); return(true); } else { try { using (Session session = new Session()) { session.Open(sessionOptions); RemoteDirectoryInfo dir = session.ListDirectory("."); session.RemoveFiles(nombreCv).Check(); } return(true); } catch (Exception e) { return(false); } } }
public void createIndicationPaths() { if (!Directory.Exists(indicationsPath)) { Directory.CreateDirectory(indicationsPath); } using (Session session = new Session()) { session.Open(sessionOptions); RemoteDirectoryInfo directory = session.ListDirectory("/indications"); foreach (RemoteFileInfo fileInfo in directory.Files) { if (!Directory.Exists(indicationsPath + '\\' + fileInfo.Name)) { Directory.CreateDirectory(indicationsPath + '\\' + fileInfo.Name); } } DirectoryInfo dirYear = new DirectoryInfo(indicationsPath); foreach (var item in dirYear.GetDirectories()) { RemoteDirectoryInfo directory2 = session.ListDirectory("/indications/" + item); foreach (RemoteFileInfo fileInfo2 in directory2.Files) { if (!Directory.Exists(indicationsPath + '\\' + item + "\\" + fileInfo2.Name)) { Directory.CreateDirectory(indicationsPath + '\\' + item + "\\" + fileInfo2.Name + "\\wets"); Directory.CreateDirectory(indicationsPath + '\\' + item + "\\" + fileInfo2.Name + "\\temps"); Directory.CreateDirectory(indicationsPath + '\\' + item + "\\" + fileInfo2.Name + "\\pressure"); } } } session.Close(); } }
/// <summary> /// SFTP 연결 버튼 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void BtnConnection_Click(object sender, EventArgs e) { TreeLocalFileList.Nodes.Clear(); TreeServerFileList.Nodes.Clear(); sessionOptions = new SessionOptions { Protocol = Protocol.Sftp, HostName = TxtAddress.Text, UserName = TxtID.Text, Password = TxtPassword.Text, PortNumber = Convert.ToInt32(TxtPort.Text), SshHostKeyFingerprint = "ssh-rsa 1024 YKV2Oy2ygc1MFwaCwYBohn9cPdrJvPg+2U1n0zJ4A6Q=", GiveUpSecurityAndAcceptAnySshHostKey = true }; using (Session session = new Session()) { session.Open(sessionOptions); RemoteDirectoryInfo directory = session.ListDirectory(@"/"); // Server에서 Root로 지정된 경로의 상대경로를 지정. 서버의 C:\부터 지정하는게 아님 //TreeServerFileList.Nodes.Add(ServerRecuresiveDirectory(session, @"/", @"/")); // 원본 TreeServerFileList.Nodes.Add(ServerRecuresiveDirectory(session, directory.Files[0].Name, directory.Files[0].FullName)); // 재귀 함수 시작 } TxtServerCurrentPath.Text = @"/"; DirectoryInfo localDirectoryInfo = new DirectoryInfo(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)); // 내 문서 절대 경로 TreeLocalFileList.Nodes.Add(LocalRecuresiveDirectory(localDirectoryInfo.FullName, localDirectoryInfo.Name)); // 재귀 함수 시작 TxtLocalCurrentPath.Text = localDirectoryInfo.FullName; }
public void setCurrentTransferSrc(RemoteFileInfo srcFile) { currentTransfer = srcFile; currentTransferSrcPath = sourcePath + '/' + srcFile.Name; // Select expedition directory currentTransferDir = session.ListDirectory(currentTransferSrcPath); }
public string[] GetDirectoryList() { try { //判斷是否為資料夾 if (!Path.HasExtension(this.currentRemotePath)) { remoteDirectoryInfo = this.session.ListDirectory(this.currentRemotePath); } else { this.currentRemotePath = this.GetParantDirectory(this.currentRemotePath, 1);//若為檔案則當前目錄改成上一層目錄 remoteDirectoryInfo = this.session.ListDirectory(this.currentRemotePath); } } catch (Exception ex) { this.ErrorMsg = "取得遠端目錄失敗: 遠端路徑:" + this.currentRemotePath + "\r錯訊訊息:" + ex.StackTrace; throw new Exception("Get directory " + this.currentRemotePath + "\r failed: " + ex.Message); } string[] directoryList = new string[remoteDirectoryInfo.Files.Count()]; for (int i = 0; i < remoteDirectoryInfo.Files.Count(); i++) { directoryList[i] = string.Format("{0}", Path.Combine(path1: this.currentRemotePath, path2: remoteDirectoryInfo.Files[i].Name)); } return(directoryList); }
private ArrayList ListFiles(String HostName, String UserName, String Password, String remotePath) { //int result = 0; Session session = null; ArrayList fileNameList = new ArrayList(); try { // Setup session options SessionOptions sessionOptions = new SessionOptions { Protocol = Protocol.Ftp, HostName = HostName, UserName = UserName, Password = Password, //HostName = "119.59.73.48", //UserName = "******", //Password = "******", // SshHostKeyFingerprint = "ssh-rsa 1024 xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx" }; using (session = new Session()) { // Connect session.Open(sessionOptions); RemoteDirectoryInfo dirInfo = session.ListDirectory(remotePath); foreach (RemoteFileInfo folder in dirInfo.Files) { if (folder.IsDirectory && folder.Name != "..") { fileNameList.Add(folder.Name); } // Console.WriteLine("File Name: {0},LastWriteTime: {1},IsDirectory: {2},File Length: {3},", file.Name, file.LastWriteTime, file.IsDirectory, file.Length); } } // return 0; } catch (Exception e) { Console.WriteLine("Error: {0}", e); // return 1; } finally { if (session != null) { session.Dispose(); } } return(fileNameList); }
static void Main() { var ftpSession = new FtpSession(); var ftpEnvironment = new FtpEnvironment(); string remote = ftpEnvironment.GetRemoteDir(); string local = ftpEnvironment.GetLocalDir(); int numberOfExpectedFiles = ftpEnvironment.GetNumberOfExpectFiles(); ftpEnvironment.SetupLocalDir(local); Console.WriteLine("Message: Writing files to {0}\n", local); try { using (Session session = new Session()) { session.Open(ftpSession.GetSessionOptions()); RemoteDirectoryInfo info = session.ListDirectory(remote); if (info.Files.Count == 0) { throw new Exception("No files present at remote end"); } TransferOptions options = new TransferOptions { FileMask = "|*/" }; int numberOfFilesRetrieved = 0; foreach (RemoteFileInfo fileInfo in info.Files) { if (IsValidFileType(fileInfo.Name)) { Console.WriteLine("Message: Getting file {0}", fileInfo.Name); session.GetFiles(session.EscapeFileMask(remote + fileInfo.Name), local, false, options) .Check(); numberOfFilesRetrieved++; } } if (numberOfFilesRetrieved != numberOfExpectedFiles) { throw new Exception("Check all files are present at remote end"); } session.Close(); } } catch (Exception ex) { Console.WriteLine("Error: {0}", ex); } }
static void Main(string[] args) { Console.WriteLine("Using WinSCP Client"); Stopwatch watch = Stopwatch.StartNew(); watch.Start(); //Connecting to WinSCP var username = "******"; var password = "******"; var host = "52.187.3.217"; int port = 22; string hostKey = "ssh-rsa 2048 59:22:9e:5b:eb:c3:6c:c0:2a:01:7f:cc:b3:1e:68:aa"; //Connecting to RebexTinySftpServer //var username = "******"; //var password = "******"; //var host = "52.187.3.217"; //int port = 22; //string hostKey = "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDQ38sCI2XLgD74f3yNLKt17uTDuA0D1RJEmE19G9UBLoJvRRwTRk8lO/pEQ1uLW69u0mC34Su+XWtt2B1TFRTFZR0sFxD5Iz/61Zw7wTZPCaufMSrWBryd5TQ+sW5l6CSyvp00WUOyRIgY+OMTS4DcFLKt0iyKdScuhCSBFcewGqceFdJPdUj62rmgLCrPfr3vZO/rQGo0ipy4mexviCljE1yOvfFCC/4e4+Fap/MLlo8ogl3aLobDisBZkgZo9VIACMyjwcpfmdcnVEvwkpLta/2QRA6eEJcDNnWl32RzHZ1CbQkMH+63EDQlbVUCCEi3Tx6bg6MJ/GLkFyPjLkdP"; // Setup session options SessionOptions sessionOptions = new SessionOptions { Protocol = Protocol.Sftp, HostName = host, PortNumber = port, UserName = username, Password = password, SshHostKeyFingerprint = hostKey }; using (Session session = new Session()) { // Connect session.Open(sessionOptions); Console.WriteLine($"IsConnected: {session.Opened}"); RemoteDirectoryInfo directory = session.ListDirectory("/C:/Agdio"); foreach (RemoteFileInfo fileInfo in directory.Files) { Console.WriteLine("{0} with size {1}, permissions {2} and last modification at {3}", fileInfo.Name, fileInfo.Length, fileInfo.FilePermissions, fileInfo.LastWriteTime); } } watch.Stop(); Console.WriteLine($"Time taken for connect: {watch.Elapsed.Seconds}s"); }
public List <string> GetFileList(string path = "/") { List <string> rstList = new List <string>(); RemoteDirectoryInfo directory = SESSION.ListDirectory(path); foreach (RemoteFileInfo fileInfo in directory.Files) { rstList.Add($"{fileInfo.Name} with size {fileInfo.Length}, permissions {fileInfo.FilePermissions} and last modification at {fileInfo.LastWriteTime}"); } return(rstList); }
private void Test(ServerConfig conf) { Session session; SessionOptions opts; UpdateMessage("Configuring WinSCP Information..."); try { opts = ConnectionUtils.GetSessionOptions(conf); } catch { UpdateMessage("Configuring WinSCP Information Failed!"); DialogResult = DialogResult.Abort; //CloseForm(); return; } UpdateMessage($"Connecting to {conf.Hostname} with username {conf.Username}"); try { session = ConnectionUtils.GetSession(opts); } catch { UpdateMessage($"Connection to {conf.Hostname} failed!"); DialogResult = DialogResult.Abort; //CloseForm(); return; } try { RemoteDirectoryInfo directory = session.ListDirectory("/"); if (directory.Files.Count > 0) { UpdateMessage($"Connection to {conf.Hostname} succeeded!"); DialogResult = DialogResult.OK; //CloseForm(); return; } else { UpdateMessage($"Connection to {conf.Hostname} failed!"); DialogResult = DialogResult.Abort; //CloseForm(); return; } } catch { UpdateMessage($"Failed to verify successful connection to {conf.Hostname} (check '/' read permissions)"); DialogResult = DialogResult.Abort; //CloseForm(); return; } finally { session.Close(); } }
private void CleanupFolder(Session session) { RemoteDirectoryInfo directoryInfo = session.ListDirectory(FolderPath); var files = directoryInfo.Files.Where(file => !file.IsDirectory).ToList(); var cutOff = DateTime.Now.AddDays(-ClearInterval); var oldfiles = files.Where(file => file.LastWriteTime < cutOff).ToList(); foreach (var file in oldfiles) { session.RemoveFiles(file.FullName); } }
public void GetRemoteFile(string Path) { if (Form1._Connected) { LWRemote.Items.Clear(); RemoteDirectoryInfo directory = Form1.session.ListDirectory(Path); string str; foreach (RemoteFileInfo fileInfo in directory.Files) { str = fileInfo.FileType.ToString() + fileInfo.FilePermissions.Text; LWRemote.Items.Add(new ListViewItem(new string[] { fileInfo.Name, str })); } } }
private void button1_Click(object sender, EventArgs e) { try { // FolderBrowserDialog ofd = new FolderBrowserDialog(); // ofd.ShowDialog(); string folderToUpload = @"C:\Users\canpy\OneDrive\Documents\GitHub\groupVolumeControl(ATLANTIS)\Installer\Release\*"; // Setup session options SessionOptions sessionOptions = new SessionOptions { Protocol = Protocol.Sftp, HostName = host, UserName = usr, Password = pw, SshHostKeyFingerprint = sshKey }; using (Session session = new Session()) { // Connect session.Open(sessionOptions); RemoteDirectoryInfo targetServerDir = session.ListDirectory("/opt/mean/public/VolumeControlUtility/test/"); Console.WriteLine(targetServerDir.ToString()); // Upload files TransferOptions transferOptions = new TransferOptions(); transferOptions.TransferMode = TransferMode.Binary; TransferOperationResult transferResult; //transferResult = session.PutFiles(@"d:\toupload\*", "/home/user/", false, transferOptions); session.RemoveFiles("/opt/mean/public/VolumeControlUtility/test/*"); transferResult = session.PutFiles(folderToUpload, "/opt/mean/public/VolumeControlUtility/test/", false, transferOptions); // Throw on any error transferResult.Check(); // Print results foreach (TransferEventArgs transfer in transferResult.Transfers) { Console.WriteLine("Upload of {0} to deployment server has succeeded", transfer.FileName); } } } catch (Exception err) { Console.WriteLine("Error: {0}", err); } }
public void Generate(Session myConnection, ExtendedTreeNode mainNode, string pathServer) { RemoteDirectoryInfo directoryInfo = myConnection.ListDirectory(pathServer); int numberOfFolders = directoryInfo.Files.Where(x => x.IsDirectory && x.Name != "..").Count(); if (numberOfFolders > 0) { ExtendedTreeNode folderNode = new ExtendedTreeNode("?"); folderNode.Text = "?"; folderNode.Name = "?"; folderNode.Tag = "Directory"; folderNode.ImageIndex = 2; folderNode.SelectedImageIndex = 2; mainNode.Nodes.Add(folderNode); } }
public FtpFileInfo[] ListFTPFiles(string Remote_FolderPath) { RemoteDirectoryInfo rdirInfo = session.ListDirectory(Remote_FolderPath); var qry = from c in rdirInfo.Files.AsEnumerable() where !(c.IsDirectory || c.IsThisDirectory || c.IsParentDirectory) select new FtpFileInfo { FullName = c.FullName, LastWriteTime = c.LastWriteTime, Length = c.Length, Name = c.Name }; return(qry.ToArray()); }
private void AddDirectory(FtpFileSystemItem parentItem, string path) { RemoteDirectoryInfo directory = session.ListDirectory(path); foreach (RemoteFileInfo item in directory.Files) { if (!item.IsParentDirectory && !item.IsThisDirectory) { var child = parentItem.AddChild(item); if (child.IsDirectory) { AddDirectory(child, child.FileInfo.FullName); } } } }
public void foldersign(string folder) { RemoteDirectoryInfo directory = Form1.session.ListDirectory(folder); foreach (RemoteFileInfo fileInfo in directory.Files) { if (fileInfo.IsDirectory && fileInfo.Name != "." && fileInfo.Name != "..") { foldersign(folder + "/" + fileInfo.Name); } else if (fileInfo.Name != "." && fileInfo.Name != "..") { sign(folder + "/" + fileInfo.Name); } } }
//------------------------------------------------------------------------------------------------------------------------------------------------------------------------ public List <string[]> GetDirectoriesAndFiles(string path) { try { List <string[]> directoriesAndFiles = new List <string[]>(); using (Session myConnection = new Session()) { myConnection.Open(MyConnectionOptions); RemoteDirectoryInfo directoryInfo = myConnection.ListDirectory(path); foreach (RemoteFileInfo fileInfo in directoryInfo.Files) { if (fileInfo.Name != "..") { string[] item = new string[6]; item[0] = fileInfo.Name; // ime filea/dir item[1] = Convert.ToString(fileInfo.Length); // veličina filea/dir item[2] = Path.GetExtension(fileInfo.Name); // ekstenzija item[3] = Convert.ToString(fileInfo.LastWriteTime); // last modified item[4] = Convert.ToString(fileInfo.IsDirectory); // provjeravam radi li se o dir ili fileu if (path.Equals("/")) { item[5] = "/" + fileInfo.FullName; // full path } else { item[5] = fileInfo.FullName; } directoriesAndFiles.Add(item); } } } return(directoriesAndFiles); } catch (Exception e) { ErrorMessage = e.Message; wasConnectionEstablished = false; throw new Exception(ErrorMessage); } }
/// <summary> /// Mocking the return of ListDirectory is impossible, literally. So it is best to isolate the untested code. /// public sealed class RemoteDirectoryInfo /// "You can only get an instance of the class by calling Session.ListDirectory." -WinSCP /// <param name="location">Location of the server to check e.g. /complete</param> /// <param name="filename">Just the filename e.g. test.csv</param> /// <param name="callback">Called once the wait is over. No parameters.</param> /// </summary> public virtual bool InDirectoryListing(string location, string filename) { RemoteDirectoryInfo directory = ftp.ListDirectory(location); if (directory != null) { foreach (RemoteFileInfo fileInfo in directory.Files) { if (fileInfo.Name == filename) { return(true); } } } return(false); }
/// <summary> /// This will connect to the Inbox/840 folder and download any notifications found there - if not previously downloaded based on our log file /// </summary> /// <param name="sessionOptions">This holds the connection information such as server and account credentials</param> /// <param name="transmissions">This holds our log file information on transfers</param> /// <param name="downloadFolder">The folder that will hold the downloaded files</param> /// <returns></returns> public static void DownloadInbox(SessionOptions sessionOptions, Dictionary <string, string> transmissions, string downloadFolder) { string folderCheck = downloadFolder.Substring(downloadFolder.Length - 1, 1); if (folderCheck != "\\") { downloadFolder = downloadFolder + "\\"; } using (Session session = new Session()) { // Connect session.Open(sessionOptions); RemoteDirectoryInfo directory = session.ListDirectory("/Inbox/840/"); TransferOptions transferOptions = new TransferOptions(); transferOptions.TransferMode = TransferMode.Binary; foreach (RemoteFileInfo fileInfo in directory.Files) { //if the length is greater than 2, there is a file for download //we will check our log file to see if this one has already been downloaded and processed if (fileInfo.Name.Length > 2) { //check to see if this is in our transmission log file if (transmissions.ContainsKey(fileInfo.Name) == false) { //we will download the file and try to match it with TransferOperationResult transferResult; transferResult = session.GetFiles("/Inbox/840/" + fileInfo.Name, downloadFolder + fileInfo.Name, false, transferOptions); // Throw on any error transferResult.Check(); // SFTP options can be logged here if needed //foreach (TransferEventArgs transfer in transferResult.Transfers) //{ // Console.WriteLine("Download of {0} succeeded", transfer.FileName); //} } } } session.Close(); } }
public static void Download(string localPath, JCompDeviceStorage jo, bool remote = true) { try { Session session = Reconnect(jo.JCompDevice, remote); RemoteDirectoryInfo directory = session.ListDirectory(jo.Path); foreach (RemoteFileInfo fileInfo in directory.Files) { Console.WriteLine(jo.Path + fileInfo.Name); /* * TransferOptions transferOptions = new TransferOptions(); * transferOptions.TransferMode = TransferMode.Binary; * transferOptions.FilePermissions = null; * transferOptions.PreserveTimestamp = false; * transferOptions.ResumeSupport.State = TransferResumeSupportState.Off; * TransferOperationResult transferResult; * transferResult = session.GetFiles(jo.ExtraPath + fileInfo.Name, localPath, false, transferOptions); * transferResult.Check(); */ } CloseRemoteSession(jo.JCompDevice); } catch (SessionLocalException sle) { string errorDetail = "WinSCP: There was an error communicating with winscp process. winscp cannot be found or executed."; errorDetail += Environment.NewLine + "Message:" + sle.Message; errorDetail += Environment.NewLine + "Target Site:" + sle.TargetSite; errorDetail += Environment.NewLine + "Inner Exception:" + sle.InnerException; errorDetail += Environment.NewLine + "Stacktrace: " + sle.StackTrace; throw sle; } catch (SessionRemoteException sre) { string errorDetail = "WinSCP: Error is reported by the remote server; Local error occurs in WinSCP console session, such as error reading local file."; errorDetail += Environment.NewLine + "Message:" + sre.Message; errorDetail += Environment.NewLine + "Target Site:" + sre.TargetSite; errorDetail += Environment.NewLine + "Inner Exception:" + sre.InnerException; errorDetail += Environment.NewLine + "Stacktrace: " + sre.StackTrace; throw sre; } catch (Exception ex) { throw ex; } }
public RemoteFileInfo GetLastFileRemoteFileInfo(RemoteDirectoryInfo directoryInfo) { // Select the most recent file var latest = directoryInfo.Files .Where(file => !file.IsDirectory) .OrderByDescending(file => file.LastWriteTime) .FirstOrDefault(); // Any file at all? if (latest == null) { throw new Exception("No file found"); } return(latest); }
public DataTable dirListingAsDataTable(string directoryToCheck) { if (directoryToCheck == string.Empty || directoryToCheck.Trim() == "") { directoryToCheck = "."; } DataTable table = new DataTable(); DataColumn name = new DataColumn("name", System.Type.GetType("System.String")); DataColumn isDirectory = new DataColumn("isDirectory", System.Type.GetType("System.String")); DataColumn length = new DataColumn("length", System.Type.GetType("System.Int64")); DataColumn lastwrite = new DataColumn("lastwrite", System.Type.GetType("System.DateTime")); table.Columns.Add(name); table.Columns.Add(isDirectory); table.Columns.Add(length); table.Columns.Add(lastwrite); /*attempt at patch for issue: in case disconnected, reconnect * System.InvalidOperationException: Session is not opened * at WinSCP.Session.CheckOpened() * at WinSCP.Session.ListDirectory(String path) * at Processor.FTPer.dirListingAsDataTable(String directoryToCheck) in c:\Users\AJordan\Desktop\Coding\Processor\FTPer.cs:line 286 * at Processor.FTPer.mostRecentDVUpload(FileType uploadType, String jobnumber) in c:\Users\AJordan\Desktop\Coding\Processor\FTPer.cs:line 305 * at Processor.ToDo.queueFiles() in c:\Users\AJordan\Desktop\Coding\Processor\ToDo.cs:line 305 */ if (!session.Opened) { session.Dispose(); this.startSession(); } RemoteDirectoryInfo dir = this.session.ListDirectory(directoryToCheck); foreach (RemoteFileInfo ftpFile in dir.Files) { DataRow row = table.NewRow(); row["name"] = ftpFile.Name; row["isDirectory"] = ftpFile.IsDirectory; row["length"] = ftpFile.Length; row["lastwrite"] = ftpFile.LastWriteTime; table.Rows.Add(row); } return(table); }
private void BgwUpload_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { panel1.Enabled = true; LocalSideFilePathBasket.Clear(); pForm2.Hide(); // BackgroundWorker 작업이 끝난 시점이라 Main Thread로 이미 작업이 옮겨왔기 때문에 Cross Thread가 발생하지 않는다. int selectedNodeLevel = TreeServerFileList.SelectedNode.Level; int selectedNodeIndex = TreeServerFileList.SelectedNode.Index; //TreeServerFileList.Nodes.RemoveAt(selectedNodeIndex); using (Session session = new Session()) { session.Open(sessionOptions); RemoteDirectoryInfo directory = session.ListDirectory(SelectedServerPath); //TreeServerFileList.Nodes.Insert(selectedNodeIndex, ServerRecuresiveDirectory(session, directory.Files[0].Name, directory.Files[0].FullName)); } }
public void Dispose() { if (this.session != null) { //RemoveSessionEvent(session); this.session.Dispose(); this.session = null; } this.sessionOptions = null; this.currentLocalPath = null; this.currentRemotePath = null; this.ErrorMsg = null; this.ProxyHost = null; this.ProxyPort = null; this.remoteDirectoryInfo = null; this.sessionOptions = null; this.transferOptions = null; }
public static void Download() { try { string ftpurl = ConfigurationManager.AppSettings["FTPUrl"]; string ftpusername = ConfigurationManager.AppSettings["FTPUsername"]; string ftppassword = ConfigurationManager.AppSettings["FTPPassword"]; string ftpSSHFingerPrint = ConfigurationManager.AppSettings["SSHFingerPrint"]; string ftpfilepath = ConfigurationManager.AppSettings["FtpFilePath"]; string Download = ConfigurationManager.AppSettings["Download"]; SessionOptions sessionOptions = new SessionOptions { Protocol = Protocol.Sftp, HostName = ftpurl, UserName = ftpusername, Password = ftppassword, PortNumber = 22, SshHostKeyFingerprint = ftpSSHFingerPrint }; using (Session session = new Session()) { session.SessionLogPath = ""; session.Open(sessionOptions); RemoteDirectoryInfo directory = session.ListDirectory("/Export/"); foreach (RemoteFileInfo fileInfo in directory.Files) { TransferOptions transferOptions = new TransferOptions(); transferOptions.TransferMode = TransferMode.Binary; transferOptions.FilePermissions = null; transferOptions.PreserveTimestamp = false; transferOptions.ResumeSupport.State = TransferResumeSupportState.Off; TransferOperationResult transferResult; transferResult = session.GetFiles("/Export/" + fileInfo.Name, Download, false, transferOptions); transferResult.Check(); } } } catch (Exception ex) { } }
protected override Task <HttpResponseMessage> ListTransportSpecificFileAsync(string folderPath) { Collection <TC.FileInfo> files = new Collection <TC.FileInfo>(); return(Task.Factory.StartNew(() => { if (!this.ValidateController()) { return this.Request.CreateResponse(HttpStatusCode.BadRequest, this.validationErrors); } try { using (Session session = new Session()) { HttpResponseMessage response; if ((response = this.OpenSession(session)).StatusCode != HttpStatusCode.OK) { return response; } RemoteDirectoryInfo remoteDirectoryInfo = session.ListDirectory(folderPath); for (int i = 0; i < remoteDirectoryInfo.Files.Count; i++) { string fileName = remoteDirectoryInfo.Files[i].Name; if (!fileName.Equals(".") && !fileName.Equals("..")) { TC.FileInfo info = new TC.FileInfo(this.ServerAddress, folderPath, fileName); files.Add(info); } } } Trace.TraceInformation("ListFile returning successfully, {0} ", folderPath); return Request.CreateResponse(files); } catch (SessionRemoteException ex) { return GetErrorResponseMessage(ex, folderPath); } })); }
private void Update(string _path, Tree <RemoteFileInfo> _tree) { try { RemoteDirectoryInfo directory = m_session.ListDirectory(_path); foreach (WinSCP.RemoteFileInfo fileInfo in directory.Files) { if (fileInfo.Name != "..") { if (fileInfo.IsDirectory) { //if the entry not cached - add the directory and then update its contents if (Tree <RemoteFileInfo> .Find(m_ignoreTree, i => i.Name == fileInfo.Name && i.IsDirectory) == null) { _tree.AddChild(new RemoteFileInfo(fileInfo)); Update(_path + "/" + fileInfo.Name, _tree.GetChild(_tree.Children.Count - 1)); } } else { //if we are not ignoring the file if (Tree <RemoteFileInfo> .Find(m_ignoreTree, i => i.Name == fileInfo.Name && !i.IsDirectory) == null) { //if the file extension is one we care about add it to list, other wise add to the ignore list //if (!m_ignoredExtensions.Contains(Utilities.GetExtensionFromFileName(fileInfo.Name))) { _tree.AddChild(new RemoteFileInfo(fileInfo)); } //else //{ // m_ignoreTree.AddChild(new RemoteFileInfo2(fileInfo)); //} } } } } } catch (Exception e) { LOG.ErrorFormat("Error: {0}", e); } }
static internal void WinScpGetLog() { LogEvent("Start Download"); using (Session session = new Session()) { // Connect session.Open(GetWinScpSession()); string remotePath = ApplicationSetting.FtpRemoteFolder; string localPath = ApplicationSetting.DownloadPath; // Get list of files in the directory RemoteDirectoryInfo directoryInfo = session.ListDirectory(remotePath); //latest file name in the table by application name var latestLogFileInDb = Path.GetFileName(unitOfWork.IISLogRepository.LatestFileName(ApplicationSetting.ApplicationName)); //get the date of the latest file from FTP var logFileDate = directoryInfo.Files .Where(w => w.Name.ToLower() == latestLogFileInDb?.ToLower()) .Select(s => s.LastWriteTime).FirstOrDefault(); // Select the files not in database table IEnumerable <RemoteFileInfo> notInLogTable = directoryInfo.Files .Where(file => !file.IsDirectory && file.LastWriteTime > logFileDate).ToList(); //// Download the selected file foreach (RemoteFileInfo fileInfo in notInLogTable) { string localFilePath = RemotePath.TranslateRemotePathToLocal( fileInfo.FullName, remotePath, localPath); string remoteFilePath = RemotePath.EscapeFileMask(fileInfo.FullName); //download TransferOperationResult transferResult = session.GetFiles(remoteFilePath, localFilePath); } LogEvent("End Download"); } }