当前位置: 首页>>代码示例>>C#>>正文


C# SftpClient.Exists方法代码示例

本文整理汇总了C#中Renci.SshNet.SftpClient.Exists方法的典型用法代码示例。如果您正苦于以下问题:C# SftpClient.Exists方法的具体用法?C# SftpClient.Exists怎么用?C# SftpClient.Exists使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在Renci.SshNet.SftpClient的用法示例。


在下文中一共展示了SftpClient.Exists方法的11个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: UploadFile

 public bool UploadFile(string filePath)
 {
     ConnectionInfo connectionInfo = new PasswordConnectionInfo(_address, ConstFields.SFTP_PORT, _username, _password);
     try
     {
         using (var sftp = new SftpClient(connectionInfo))
         {
             sftp.Connect();
             using (var file = File.OpenRead(filePath))
             {
                 if (!sftp.Exists(ConstFields.TEMP_PRINT_DIRECTORY))
                 {
                     sftp.CreateDirectory(ConstFields.TEMP_PRINT_DIRECTORY);
                 }
                 sftp.ChangeDirectory(ConstFields.TEMP_PRINT_DIRECTORY);
                 string filename = Path.GetFileName(filePath);
                 sftp.UploadFile(file, filename);
             }
             sftp.Disconnect();
         }
     }
     catch (Renci.SshNet.Common.SshConnectionException)
     {
         Console.WriteLine("Cannot connect to the server.");
         return false;
     }
     catch (System.Net.Sockets.SocketException)
     {
         Console.WriteLine("Unable to establish the socket.");
         return false;
     }
     catch (Renci.SshNet.Common.SshAuthenticationException)
     {
         Console.WriteLine("Authentication of SSH session failed.");
         return false;
     }
     return true;
 }
开发者ID:wj88808886,项目名称:OSU_PrintingHelper_Windows,代码行数:38,代码来源:NetworkHandler.cs

示例2: CreateDirectoriesRecursively

        private static void CreateDirectoriesRecursively(string directory, SftpClient sftp)
        {
            if (sftp.Exists(directory) == false)
            {
                // try creating one above, in case we need it:
                var directoryAbove = FlatRedBall.IO.FileManager.GetDirectory(directory, FlatRedBall.IO.RelativeType.Relative);

                CreateDirectoriesRecursively(directoryAbove, sftp);

                sftp.CreateDirectory(directory);
            }
        }
开发者ID:vchelaru,项目名称:FlatRedBall,代码行数:12,代码来源:SftpManager.cs

示例3: ListFiles

        /// <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;
        }
开发者ID:ElanHasson,项目名称:SSIS-Extensions,代码行数:53,代码来源:SFTPConnection.cs

示例4: DownloadFiles

        /// <summary>
        /// Downloads the files.
        /// </summary>
        /// <param name="fileList">The file list.</param>
        /// <param name="failRemoteNotExists">if set to <c>true</c> [fail remote not exists].</param>
        /// <exception cref="System.Exception">
        /// Local File Already Exists.
        /// </exception>
        public void DownloadFiles(List<ISFTPFileInfo> fileList)
        {
            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);

                    // Download each file
                    foreach (SFTPFileInfo filePath in fileList)
                    {
                        if (!sftp.Exists(filePath.RemotePath))
                        {
                            this.Log(String.Format("Remote Path Does Not Exist: [{0}].", this.hostName), LogLevel.Verbose);
                            if (this.stopOnFailure)
                                throw new Exception(String.Format("Remote Path Does Not Exist: [{0}]", filePath.RemotePath));
                            else
                                continue;
                        }

                        if (Directory.Exists(filePath.LocalPath))
                            filePath.LocalPath = Path.Combine(filePath.LocalPath, filePath.RemotePath.Substring(filePath.RemotePath.LastIndexOf("/") + 1));

                        // Can we overwrite the local file
                        if (!filePath.OverwriteDestination && File.Exists(filePath.LocalPath))
                            throw new Exception("Local File Already Exists.");

                        this.Log(String.Format("Downloading File: [{0}] -> [{1}].", filePath.RemotePath, filePath.LocalPath), LogLevel.Minimal);
                        using (FileStream fileStream = File.OpenWrite(filePath.LocalPath))
                        {
                            sftp.DownloadFile(filePath.RemotePath, fileStream);
                        }
                        this.Log(String.Format("File Downloaded: [{0}]", filePath.LocalPath), LogLevel.Verbose);
                    }
                }
                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 Download: ", ex);
            }
        }
开发者ID:ElanHasson,项目名称:SSIS-Extensions,代码行数:55,代码来源:SFTPConnection.cs

示例5: UploadFiles

        /// <summary>
        /// Uploads the files.
        /// </summary>
        /// <param name="fileList">The file list.</param>
        /// <exception cref="System.Exception">Remote File Already Exists.</exception>
        public void UploadFiles(List<ISFTPFileInfo> fileList)
        {
            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);

                    // Upload each file
                    foreach (SFTPFileInfo sftpFile in fileList)
                    {
                        FileInfo fileInfo = new FileInfo(sftpFile.LocalPath);
                        if (sftpFile.RemotePath.EndsWith("/"))
                            sftpFile.RemotePath = Path.Combine(sftpFile.RemotePath, fileInfo.Name).Replace(@"\", "/");

                        // if file exists can we overwrite it.
                        if (sftp.Exists(sftpFile.RemotePath))
                        {
                            if (sftpFile.OverwriteDestination)
                            {
                                this.Log(String.Format("Removing File: [{0}].", sftpFile.RemotePath), LogLevel.Verbose);
                                sftp.Delete(sftpFile.RemotePath);
                                this.Log(String.Format("Removed File: [{0}].", sftpFile.RemotePath), LogLevel.Verbose);
                            }
                            else
                            {
                                if (this.stopOnFailure)
                                    throw new Exception("Remote File Already Exists.");
                            }
                        }

                        using (FileStream file = File.OpenRead(sftpFile.LocalPath))
                        {
                            this.Log(String.Format("Uploading File: [{0}] -> [{1}].", fileInfo.FullName, sftpFile.RemotePath), LogLevel.Minimal);
                            sftp.UploadFile(file, sftpFile.RemotePath);
                            this.Log(String.Format("Uploaded File: [{0}] -> [{1}].", fileInfo.FullName, sftpFile.RemotePath), LogLevel.Verbose);
                        }
                    }
                }
                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 Upload: ", ex);
            }
        }
开发者ID:ElanHasson,项目名称:SSIS-Extensions,代码行数:56,代码来源:SFTPConnection.cs

示例6: CreateDirectory

 private void CreateDirectory(SftpClient client, string sourceFolderName, string destination)
 {
     var arr = sourceFolderName.Split(DeployUtil.TransferFolder.ToCharArray());
     var relativeFolder = arr.Last();
     var destinationPath = Path.Combine(destination, relativeFolder);
     if (!client.Exists(destinationPath))
     {
         client.CreateDirectory(destination);
         client.ChangeDirectory(destination);
     }
 }
开发者ID:dragon753,项目名称:Deployer,代码行数:11,代码来源:DeployOperation.cs

示例7: Main

        private static void Main(string[] args)
        {
            string shufSharp = "ShufflySharp";

            var projs = new[] {
                                      shufSharp + @"\Libraries\CommonLibraries\",
                                      shufSharp + @"\Libraries\CommonShuffleLibrary\",
                                      shufSharp + @"\Libraries\ShuffleGameLibrary\",
                                      shufSharp + @"\Libraries\NodeLibraries\",
                                      shufSharp + @"\Servers\ServerManager\", 
                                      shufSharp + @"\Models\",
                                      shufSharp + @"\Client\",
                                      shufSharp + @"\ClientLibs\",
                                      shufSharp + @"\ServerSlammer\",
                              };
            var pre = Directory.GetCurrentDirectory() + @"\..\..\..\..\..\";

            foreach (var proj in projs) {
#if DEBUG
                var from = pre + proj + @"\bin\debug\" + proj.Split(new[] {"\\"}, StringSplitOptions.RemoveEmptyEntries).Last() + ".js";
#else
                var from = pre + proj + @"\bin\release\" + proj.Split(new[] {"\\"}, StringSplitOptions.RemoveEmptyEntries).Last() + ".js";
#endif
                var to = pre + shufSharp + @"\output\" + proj.Split(new[] {"\\"}, StringSplitOptions.RemoveEmptyEntries).Last() + ".js";

                if (File.Exists(to)) tryDelete(to);
                tryCopy(from, to);
            }

            //client happens in buildsite.cs
            var depends = new Dictionary<string, Application>(); 
            depends.Add(shufSharp + @"\Servers\ServerManager\",
                        new Application(true,
                                        new List<string> {
                                                                 @"./NodeLibraries.js",
                                                                 @"./CommonLibraries.js",
                                                                 @"./CommonShuffleLibrary.js",
                                                                 @"./ShuffleGameLibrary.js",
                                                                 @"./Models.js",
                                                                 @"./RawDeflate.js",
                                                         })); 


            depends.Add(shufSharp + @"\Libraries\CommonShuffleLibrary\",
                        new Application(false,
                                        new List<string> {
                                                                 @"./NodeLibraries.js",
                                                         }));
            depends.Add(shufSharp + @"\Libraries\NodeLibraries\", new Application(true, new List<string> {}));
            depends.Add(shufSharp + @"\Libraries\CommonLibraries\", new Application(false, new List<string> {}));
            depends.Add(shufSharp + @"\ClientLibs\", new Application(false, new List<string> {}));
            depends.Add(shufSharp + @"\ServerSlammer\",
                        new Application(true,
                                        new List<string> {
                                                                 @"./NodeLibraries.js",
                                                                 @"./Models.js",
                                                                 @"./ClientLibs.js",
                                                         }));
            depends.Add(shufSharp + @"\Models\", new Application(false, new List<string> {}));
            depends.Add(shufSharp + @"\Libraries\ShuffleGameLibrary\", new Application(false, new List<string> {}));
            depends.Add(shufSharp + @"\Client\",
                        new Application(false,
                                        new List<string> {}));

#if FTP
            string loc = ConfigurationSettings.AppSettings["web-ftpdir"];
            Console.WriteLine("connecting ftp");
            /*   Ftp webftp = new Ftp();
            webftp.Connect(ConfigurationSettings.AppSettings["web-ftpurl"]);
            webftp.Login(ConfigurationSettings.AppSettings["web-ftpusername"], ConfigurationSettings.AppSettings["web-ftppassword"]);

            Console.WriteLine("connected");

            webftp.Progress += (e, c) =>
            {
                var left = Console.CursorLeft;
                var top = Console.CursorTop;

                Console.SetCursorPosition(65, 5);
                Console.Write("|");

                for (int i = 0; i < c.Percentage / 10; i++)
                {
                    Console.Write("=");
                }
                for (int i = (int)(c.Percentage / 10); i < 10; i++)
                {
                    Console.Write("-");
                }
                Console.Write("|");

                Console.Write(c.Percentage + "  %  ");
                Console.WriteLine();
                Console.SetCursorPosition(left, top);
            };
*/
            string serverloc = ConfigurationSettings.AppSettings["server-ftpdir"];
            string serverloc2 = ConfigurationSettings.AppSettings["server-web-ftpdir"];
            Console.WriteLine("connecting server ftp");
            SftpClient client = new SftpClient(ConfigurationSettings.AppSettings["server-ftpurl"], ConfigurationSettings.AppSettings["server-ftpusername"], ConfigurationSettings.AppSettings["server-ftppassword"]);
//.........这里部分代码省略.........
开发者ID:noobouse,项目名称:ShufflySharp,代码行数:101,代码来源:Program.cs

示例8: DoexRemoteFolderExist

 public static bool DoexRemoteFolderExist(string host, string user, string password, string remotePath)
 {
     using (SftpClient client = new SftpClient(host, user, password))
     {
         client.KeepAliveInterval = TimeSpan.FromSeconds(60);
         client.ConnectionInfo.Timeout = TimeSpan.FromMinutes(180);
         client.OperationTimeout = TimeSpan.FromMinutes(180);
         client.Connect();
         bool r = client.Exists(remotePath);
         client.Disconnect();
         return r;
     }
 }
开发者ID:wangn6,项目名称:rep2,代码行数:13,代码来源:SSHWrapper.cs

示例9: Execute

        private void Execute()
        {
            var keyPath = textBoxFile.Text;
            var host = textBoxHost.Text;
            var user = textBoxUser.Text;
            var pass = textBoxPass.Text;

            Action _execute = () =>
            {
                try
                {
                    //Read Key
                    Status("opening key");
                    FileStream file = File.OpenRead(keyPath);

                    //Connect to SFTP
                    Status("sftp connecting");
                    SftpClient sftp = new SftpClient(host, user, pass);
                    sftp.Connect();

                    //users home directory
                    string homepath = "/home/" + user + "/";
                    if (user == "root")
                    {
                        homepath = "/root/";
                    }

                    //Find authorized keys
                    string authKeys = homepath + ".ssh/authorized_keys";
                    if (!sftp.Exists(authKeys))
                    {
                        Status("creating");
                        if (!sftp.Exists(homepath + ".ssh"))
                            sftp.CreateDirectory(homepath + ".ssh");
                        sftp.Create(authKeys);
                    }

                    //Download
                    Status("downloading");
                    Stream stream = new MemoryStream();
                    sftp.DownloadFile(authKeys, stream);
                    Status("downloaded");

                    //Read
                    byte[] buffer = new byte[10240]; //No key should be this large
                    int length = file.Read(buffer, 0, buffer.Length);

                    //Validate
                    String strKey;
                    if (length < 20)
                    {
                        Status("Invalid Key (Length)");
                        return;
                    }
                    if (buffer[0] == (byte) 's' && buffer[1] == (byte) 's' && buffer[2] == (byte) 'h' &&
                        buffer[3] == (byte) '-' && buffer[4] == (byte) 'r' && buffer[5] == (byte) 's' &&
                        buffer[6] == (byte) 'a')
                    {
                        strKey = Encoding.ASCII.GetString(buffer, 0, length).Trim();
                    }
                    else
                    {
                        Status("Invalid Key (Format)");
                        return;
                    }

                    stream.Seek(0, SeekOrigin.Begin);
                    StreamReader reader = new StreamReader(stream);

                    //Check for key that might already exist
                    while (!reader.EndOfStream)
                    {
                        var line = reader.ReadLine().Trim();
                        if (line == strKey)
                        {
                            Status("key already exists");
                            return;
                        }
                    }

                    //Check new line
                    if (stream.Length != 0)
                    {
                        stream.Seek(0, SeekOrigin.End);
                        stream.WriteByte((byte) '\n');
                    }
                    else
                    {
                        stream.Seek(0, SeekOrigin.End);
                    }

                    //Append
                    Status("appending");
                    stream.Write(buffer, 0, length);

                    //Upload
                    Status("uploading");
                    stream.Seek(0, SeekOrigin.Begin);
                    sftp.UploadFile(stream, authKeys);
                    Status("done");
//.........这里部分代码省略.........
开发者ID:splitice,项目名称:SSHKeyTransfer,代码行数:101,代码来源:Form1.cs

示例10: Main

        private static void Main(string[] args)
        {
            string llo = "LampLightOnlineSharp";
            var pre = Directory.GetCurrentDirectory() + @"\..\..\..\..\..\..\";

            /*


            var projs = new[]
                { 
                    [email protected]"\LampLightOnlineClient\",
                    [email protected]"\LampLightOnlineServer\",
                };

            foreach (var proj in projs)
            {
#if DEBUG
                var from = pre + proj + @"\bin\debug\" + proj.Split(new[] { "\\" }, StringSplitOptions.RemoveEmptyEntries).Last() + ".js";
#else
                var from = pre + proj + @"\bin\release\" + proj.Split(new[] {"\\"}, StringSplitOptions.RemoveEmptyEntries).Last() + ".js";
#endif
                var to = pre + llo + @"\output\" + proj.Split(new[] { "\\" }, StringSplitOptions.RemoveEmptyEntries).Last() + ".js";
                if (File.Exists(to)) File.Delete(to);
                File.Copy(from, to);
            }
*/

            //client happens in buildsite.cs
            var depends = new Dictionary<string, Application> {
                                                                      /*{
                        [email protected]"\Servers\AdminServer\", new Application(true, "new AdminServer.AdminServer();", new List<string>
                            {
                                @"./CommonLibraries.js",
                                @"./CommonServerLibraries.js",
                                @"./Models.js",
                            })
                    }*/
                                                                      {
                                                                              "MM.ChatServer", new Application(true,
                                                                                                               new List<string> {
                                                                                                                                        @"./CommonAPI.js",
                                                                                                                                        @"./ServerAPI.js",
                                                                                                                                        @"./CommonLibraries.js",
                                                                                                                                        @"./CommonServerLibraries.js",
                                                                                                                                        @"./Models.js",
                                                                                                                                })
                                                                      }, {
                                                                                 "MM.GameServer", new Application(true,
                                                                                                                  new List<string> {
                                                                                                                                           @"./CommonAPI.js",
                                                                                                                                           @"./MMServerAPI.js",
                                                                                                                                           @"./CommonLibraries.js",
                                                                                                                                           @"./CommonServerLibraries.js",
                                                                                                                                           @"./CommonClientLibraries.js",
                                                                                                                                           @"./MMServer.js",
                                                                                                                                           @"./Games/ZombieGame/ZombieGame.Common.js",
                                                                                                                                           @"./Games/ZombieGame/ZombieGame.Server.js",
                                                                                                                                           @"./Models.js",
                                                                                                                                           @"./RawDeflate.js",
                                                                                                                                   }) {}
                                                                         }, {
                                                                                    "MM.GatewayServer", new Application(true,
                                                                                                                        new List<string> {
                                                                                                                                                 @"./CommonAPI.js",
                                                                                                                                                 @"./ServerAPI.js",
                                                                                                                                                 @"./CommonLibraries.js",
                                                                                                                                                 @"./CommonServerLibraries.js",
                                                                                                                                                 @"./MMServerAPI.js",
                                                                                                                                                 @"./MMServer.js",
                                                                                                                                                 @"./Games/ZombieGame/ZombieGame.Common.js",
                                                                                                                                                 @"./Games/ZombieGame/ZombieGame.Server.js",
                                                                                                                                                 @"./Models.js",
                                                                                                                                         })
                                                                            }, {
                                                                                       "MM.HeadServer", new Application(true,
                                                                                                                        new List<string> {
                                                                                                                                                 @"./CommonAPI.js",
                                                                                                                                                 @"./ServerAPI.js",
                                                                                                                                                 @"./CommonLibraries.js",
                                                                                                                                                 @"./CommonServerLibraries.js",
                                                                                                                                                 @"./Models.js",
                                                                                                                                         })
                                                                               }, {
                                                                                          "SiteServer", new Application(true,
                                                                                                                        new List<string> {
                                                                                                                                                 @"./CommonLibraries.js",
                                                                                                                                                 @"./CommonServerLibraries.js",
                                                                                                                                                 @"./Models.js",
                                                                                                                                         })
                                                                                  },
                                                                      {"Client", new Application(false, new List<string> {})},
                                                                      {"CommonWebLibraries", new Application(false, new List<string> {})},
                                                                      {"CommonLibraries", new Application(false, new List<string> {})},
                                                                      {"CommonClientLibraries", new Application(false, new List<string> {})},
                                                                      {"CommonServerLibraries", new Application(false, new List<string> {})},
                                                                      {"MMServer", new Application(false, new List<string> {})},
                                                                      {"MMServerAPI", new Application(false, new List<string> {})},
                                                                      {"ClientAPI", new Application(false, new List<string> {})},
                                                                      {"ServerAPI", new Application(false, new List<string> {})},
                                                                      {"CommonAPI", new Application(false, new List<string> {})},
//.........这里部分代码省略.........
开发者ID:dested,项目名称:LampLightOnlineSharp,代码行数:101,代码来源:Program.cs

示例11: CreatSSHDir

 private static void CreatSSHDir(SftpClient ssh, string file)
 {
     var newDir = Tools.Misc.GetUnixDirecoryOfFile(file);
     if (ssh.Exists(newDir)) return;
     string[] dirs = new string[newDir.ToCharArray().Count(x => x == '/')];
     dirs[0] = newDir;
     for (int i = 1; i < dirs.Count(); i++)
     {
         dirs[i] = Tools.Misc.GetUnixDirecoryOfFile(dirs[i - 1]);
     }
     for (int i = dirs.Count()-1; i >= 0; i--)
     {
         if (ssh.Exists(dirs[i])) continue;
         ssh.CreateDirectory(dirs[i]);
     }
 }
开发者ID:hmaster20,项目名称:mRemoteNC,代码行数:16,代码来源:UI.Window.SSHTransfer.cs


注:本文中的Renci.SshNet.SftpClient.Exists方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。