Get() public method

Gets reference to remote file or directory.
Client is not connected. was not found on the remote host. is null. The method was called after the client was disposed.
public Get ( string path ) : SftpFile
path string The path.
return SftpFile
        /// <summary>
        /// Lists the files.
        /// </summary>
        /// <param name="remotePath">The remote path.</param>
        /// <param name="failRemoteNotExists">if set to <c>true</c> [fail remote not exists].</param>
        /// <returns></returns>
        /// <exception cref="System.Exception"></exception>
        public List<IRemoteFileInfo> ListFiles(string remotePath)
        {
            List<IRemoteFileInfo> fileList = new List<IRemoteFileInfo>();
            try
            {
                this.Log(String.Format("Connecting to Host: [{0}].", this.hostName), LogLevel.Minimal);
                using (SftpClient sftp = new SftpClient(this.hostName, this.portNumber, this.userName, this.passWord))
                {
                    sftp.Connect();
                    this.Log(String.Format("Connected to Host: [{0}].", this.hostName), LogLevel.Verbose);

                    if (!sftp.Exists(remotePath))
                    {
                        this.Log(String.Format("Remote Path Does Not Exist: [{0}].", this.hostName), LogLevel.Verbose);
                        if (this.stopOnFailure)
                            throw new Exception(String.Format("Invalid Path: [{0}]", remotePath));
                    }
                    else
                    {
                        this.Log(String.Format("Listing Files: [{0}].", remotePath), LogLevel.Minimal);
                        this.Log(String.Format("Getting Attributes: [{0}].", remotePath), LogLevel.Verbose);

                        SftpFile sftpFileInfo = sftp.Get(remotePath);
                        if (sftpFileInfo.IsDirectory)
                        {
                            this.Log(String.Format("Path is a Directory: [{0}].", remotePath), LogLevel.Verbose);
                            IEnumerable<SftpFile> dirList = sftp.ListDirectory(remotePath);
                            foreach (SftpFile sftpFile in dirList)
                                fileList.Add(this.CreateFileInfo(sftpFile));
                        }
                        else
                        {
                            this.Log(String.Format("Path is a File: [{0}].", remotePath), LogLevel.Verbose);
                            fileList.Add(this.CreateFileInfo(sftpFileInfo));
                        }
                    }
                }
                this.Log(String.Format("Disconnected from Host: [{0}].", this.hostName), LogLevel.Minimal);
            }
            catch (Exception ex)
            {
                this.Log(String.Format("Disconnected from Host: [{0}].", this.hostName), LogLevel.Minimal);
                this.ThrowException("Unable to List: ", ex);
            }
            return fileList;
        }
Example #2
0
        public static void SSHTest()
        {
            string[] list;

            ConnectionInfo ConnNfo = new ConnectionInfo("10.26.2.136", 22, "root",
               new AuthenticationMethod[]{

                // Pasword based Authentication
                new PasswordAuthenticationMethod("root","adminadmin_2")

                // Key Based Authentication (using keys in OpenSSH Format)
                //new PrivateKeyAuthenticationMethod("username",new PrivateKeyFile[]{
                //    new PrivateKeyFile(@"..\openssh.key","passphrase")
                //}
               });

            using (var sshclient = new SshClient(ConnNfo))
            {
                sshclient.Connect();

                // quick way to use ist, but not best practice - SshCommand is not Disposed, ExitStatus not checked...
                Console.WriteLine(sshclient.CreateCommand("cd /tmp && ls -lah").Execute());
                Console.WriteLine(sshclient.CreateCommand("pwd").Execute());
                string output = sshclient.CreateCommand("cd /data1/strongmail/log && find strongmail-monitor* -maxdepth 1 -mtime -1").Execute();

                list = output.Split(Environment.NewLine.ToCharArray(), StringSplitOptions.RemoveEmptyEntries);

                foreach (string file in list)
                {
                    Console.WriteLine("File: " + file);
                }

                sshclient.Disconnect();
            }

            Console.Write("Attempt to download file.");
            // Upload A File
            using (var sftp = new SftpClient(ConnNfo))
            {

                sftp.Connect();
                sftp.ChangeDirectory("/data1/strongmail/log");

                foreach (string file in list)
                {
                    string fullPath = @"D:\Temp\StrongView\" + file;

                    var x = sftp.Get(file);
                    byte[] fileBytes = new byte[x.Length];

                    using (var dwnldfileStream = new System.IO.MemoryStream(fileBytes))
                    {

                        sftp.DownloadFile(file, dwnldfileStream);
                        //System.IO.File.WriteAllBytes(@"d:\temp\strongview\bytes\" + file, fileBytes);

                        //var xmlr = System.Xml.XmlReader.Create(dwnldfileStream);

                        //while (xmlr.Read()) {
                        //    if (xmlr.NodeType.Equals(System.Xml.XmlNodeType.Element) && xmlr.Name.Equals("QueueInfo")) {
                        //        string processid = xmlr.GetAttribute("PID");
                        //        while(!xmlr.)
                        //    }

                        //}

                        string text = ConnNfo.Encoding.GetString(fileBytes);
                        XDocument doc = XDocument.Parse("<root>" + text + "</root>");
                        var smtpQueue = doc.Descendants("QueueInfo").Where(xx => xx.Element("Protocol").Value.Equals("SMTP"));
                        var serverInfo = doc.Descendants("ServerInfo");

                        var wrtr = doc.CreateWriter();

                        System.Text.StringBuilder sb = new System.Text.StringBuilder();

                        using (System.Xml.XmlWriter wr = System.Xml.XmlWriter.Create(sb, new System.Xml.XmlWriterSettings() { ConformanceLevel = System.Xml.ConformanceLevel.Fragment }))
                        {

                            wr.WriteStartElement("root");
                            serverInfo.First().WriteTo(wr);

                            foreach (XElement xl in smtpQueue)
                            {
                                xl.WriteTo(wr);
                            }

                            wr.WriteEndElement();
                        }
                        string PID = smtpQueue.Attributes().First().Value.ToString();

                        System.IO.File.WriteAllText(@"d:\temp\strongview\docs\" + PID + ".xml", sb.ToString());

                    }

                }

                sftp.Disconnect();
            }
            Console.WriteLine("Done!");
            //Console.ReadKey();
        }