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


C# SftpClient.ChangeDirectory方法代码示例

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


在下文中一共展示了SftpClient.ChangeDirectory方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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: SFTP

        public SFTP(Uri targetServer,string password)
        {
            _sftp = new SftpClient(targetServer.Host,targetServer.Port,
                targetServer.UserInfo,
                password);

            log.InfoFormat("SFTP - Connecting to {0}", targetServer);
            _sftp.Connect();
            log.InfoFormat("SFTP - Changing dir to {0}", targetServer.LocalPath);
            _sftp.ChangeDirectory(targetServer.LocalPath);
        }
开发者ID:1aurent,项目名称:CloudBackup,代码行数:11,代码来源:SFTP.cs

示例3: SSHTest

        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();
//.........这里部分代码省略.........
开发者ID:shovelheadfxe,项目名称:DevLab,代码行数:101,代码来源:Code.cs

示例4: PushFileSFTP

        private StdResult<NoType> PushFileSFTP(string localFilePath, string distantDirectory)
        {
            if (!distantDirectory.StartsWith("/"))
                distantDirectory = string.Concat("/", distantDirectory);
            string distantPath = string.Format("ftp://{0}{1}", Host, distantDirectory);
            LogDelegate(string.Format("[FTP] Distant path: {0}", distantPath));
            try
            {
                //new SftpClient(Host, 22, Login, Pwd)

                using (var sftp = new SftpClient(new PasswordConnectionInfo(Host, 22, Login, Pwd)))
                {

                    sftp.HostKeyReceived += sftp_HostKeyReceived;
                    sftp.Connect();
                    sftp.ChangeDirectory(distantDirectory);
                    FileInfo fi = new FileInfo(localFilePath);
                    string distantFullPath = string.Format("{0}{1}", distantDirectory, fi.Name);
                    LogDelegate(string.Format("[FTP] ConnectionInfo : sftp.ConnectionInfo.IsAuthenticated:{0}, distant directory: {1}, username:{2}, host:{3}, port:{4}, distantPath:{5}",
                        sftp.ConnectionInfo.IsAuthenticated,
                        distantDirectory,
                        sftp.ConnectionInfo.Username,
                        sftp.ConnectionInfo.Host,
                        sftp.ConnectionInfo.Port,
                        distantFullPath));
                    //var sftpFiles = sftp.ListDirectory(distantDirectory);
                    //FileStream local = File.OpenRead(localFilePath);
                    //sftp.UploadFile(sr.BaseStream, distantDirectory, null);
                    using (StreamReader sr = new StreamReader(localFilePath))
                    {
                        LogDelegate(string.Format("[FTP] File being sent : {0} bytes.", sr.BaseStream.Length));
                        sftp.UploadFile(sr.BaseStream, distantFullPath);
                    }
                }
                LogDelegate(string.Format("[FTP] File Sent successfully."));
                return StdResult<NoType>.OkResult;

            }
            catch (Exception e)
            {
                if (LogDelegate != null)
                {
                    Mailer mailer = new Mailer();
                    mailer.LogDelegate = LogDelegate;
                    Exception exception = e;
                    while (exception != null)
                    {
                        LogDelegate("[FTP] Exception envoi : " + exception.Message + " " + exception.StackTrace);
                        exception = e.InnerException;
                    }
                    string emailConf = ConfigurationManager.AppSettings["NotificationEmail"];
                    mailer.SendMail(emailConf, "[Canal Collecte] Erreur FTP!", exception.Message + "<br/>" + e.StackTrace, null, ConfigurationManager.AppSettings["NotificationEmail_CC"]);

                }
                return StdResult<NoType>.BadResultFormat("[FTP] Exception envoi: {0} /// {1}", e.Message);
            }
        }
开发者ID:BlueInt32,项目名称:bundle-report,代码行数:57,代码来源:FTP.cs

示例5: 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

示例6: doUpload

        void doUpload(object sender, Renci.SshNet.Common.ShellDataEventArgs e)
        {
            var line = Encoding.UTF8.GetString(e.Data);
            var arr = line.Split(Environment.NewLine.ToCharArray()).Where(x => !string.IsNullOrEmpty(x)).ToList();

            //拿到路径之后开始上传
            var remoteBasePath = arr[1];

            using (var sftp = new SftpClient(server,port, user, pwd))
            {
                sftp.Connect();

                foreach (var file in fileList)
                {
                    string uploadfn = file;
                    var fileName = Path.GetFileName(file);
                    sftp.ChangeDirectory(remoteBasePath);
                    using (var uplfileStream = System.IO.File.OpenRead(uploadfn))
                    {
                        sftp.UploadFile(uplfileStream, fileName, true);
                    }

                    showLine(string.Format(" file===>{0}  uploaed", file));
                }
                sftp.Disconnect();
            }
            shellStream.DataReceived -= doUpload;
            shellStream.DataReceived += ShellStream_DataReceived;
        }
开发者ID:dragon753,项目名称:Deployer,代码行数:29,代码来源:SSHForm.cs

示例7: sftpConnect

        /// <summary>
        /// This function will connect to the SFTP server for Paymentus
        /// Once connected it will upload the 2 files.
        /// </summary>
        private static void sftpConnect()
        {
            client = new Renci.SshNet.SftpClient(sftpHost, sftpPort, sftpUsername, new PrivateKeyFile(new MemoryStream(Encoding.ASCII.GetBytes(sftpKeyFile)),"MoneyBag$"));
            try
            {
                client.Connect();
                client.ChangeDirectory(uploadPath);
                using (Stream fin = File.OpenRead(outputControlFullName)) {
                    try
                    {
                        client.UploadFile(fin, outputControlFileName);
                    }
                    catch (Exception e) {

                        body = body + "Threw an exception: " + e.Message.ToString() + (char)13 + (char)10;
                        Console.WriteLine(string.Format("exception...{0}", e));
                    }
                }
                using (Stream fin = File.OpenRead(outputFileFullName))
                {
                    try{
                        client.UploadFile(fin, outputFileName);
                    }
                    catch (Exception e) {

                        body = body + "Threw an exception: " + e.Message.ToString() + (char)13 + (char)10;
                        Console.WriteLine(string.Format("exception...{0}", e));
                    }
                }
            }
            catch (Exception e)
            {
                body = body + "Threw an exception: " + e.Message.ToString() + (char)13 + (char)10;
                Console.WriteLine(string.Format("exception...{0}", e));
            }
        }
开发者ID:robertmcconnell2007,项目名称:CCCommunications,代码行数:40,代码来源:Program.cs

示例8: sftpConnect

 /// <summary>
 /// This function will connect to the SFTP server for Paymentus
 /// Once connected it will upload the 2 files.
 /// </summary>
 private static void sftpConnect()
 {
     client = new Renci.SshNet.SftpClient(sftpHost, sftpPort, sftpUsername, new PrivateKeyFile(new MemoryStream(Encoding.ASCII.GetBytes(sftpKeyFile)), "MoneyBag$"));
     client.Connect();
     client.ChangeDirectory(uploadPath);
 }
开发者ID:robertmcconnell2007,项目名称:CCCommunications,代码行数:10,代码来源:Program.cs

示例9: combineAdd


//.........这里部分代码省略.........
                               {
                                   ad.ad_details[0].Images[0].ServerUrl = ImagePath;
                                   ad.ad_details[0].Images[0].IsServerUploaded = true;

                               }
                               Old.ad_details.Add(ad.ad_details[0]);
                           }
                           ad.ad_details = Old.ad_details;
                           if (Old.publisherUrl.Contains(ad.publisherUrl[0])) ad.publisherUrl = Old.publisherUrl;
                           else
                           {
                               Old.publisherUrl.Add(ad.publisherUrl[0]);
                               ad.publisherUrl = Old.publisherUrl;
                           }
                           if (Old.advertiserUrl.Contains(ad.advertiserUrl[0])) ad.advertiserUrl = Old.advertiserUrl;
                           else
                           {
                               Old.advertiserUrl.Add(ad.advertiserUrl[0]);
                               ad.advertiserUrl = Old.advertiserUrl;
                           }

                           ad.Update(ad);
                       }
                       catch { }

                   }
                   else
                   {

                       // ad.publisherUrl = new List<string> { publisherUrl };
                       try
                       {
                           //int index = Old.ad_details.FindIndex(a => a.advertiserUrl == ad.advertiserUrl[0]);
                           string ImagePath = ad.Id + "_" + 0 + "_" + 0+".jpg";
                           if (UploadImage(ImagePath, ad.ad_details[0].Images[0].ImageUrl))
                           {   ad.ad_details[0].Images[0].ServerUrl = ImagePath;
                               ad.ad_details[0].Images[0].IsServerUploaded = true;
                           }
                           ad.Insert(ad);
                       }
                       catch { }

                   }

               }
               */
        internal static bool UploadImage(string FileName, string ImageUrl)
        {
            try
            {

                using (WebClient webClient = new WebClient())
                {
                    webClient.DownloadFile(new Uri(ImageUrl), FileName);
                }

                const int port = 22;
                const string host = "66.85.92.2";
                const string username = "root";
                const string password = "fuckoff321";
                const string workingdirectory = "/var/www/ad_images/";
                // const string uploadfile = path;

                Console.WriteLine("Creating client and connecting");
                if (System.IO.File.Exists(FileName))
                {
                    using (var client = new SftpClient(host, port, username, password))
                    {
                        client.Connect();
                        client.ChangeDirectory(workingdirectory);
                        //var listDirectory = client.ListDirectory(workingdirectory);

                        //foreach (var fi in listDirectory)
                        //{
                        //    Console.WriteLine(" - " + fi.Name);
                        //}

                        using (var fileStream = new FileStream(FileName, FileMode.Open))
                        {
                            Console.WriteLine("Uploading {0} ({1:N0} bytes)",
                                                FileName, fileStream.Length);
                            client.BufferSize = 4 * 1024; // bypass Payload error large files

                            client.UploadFile(fileStream, Path.GetFileName(FileName));

                        }
                        try
                        {
                            System.IO.File.Delete(FileName);

                        }
                        catch (Exception ex)
                        { }
                        return true;
                    }
                }
                return false;
            }
            catch { return false; }
        }
开发者ID:azhard4int,项目名称:crawlers,代码行数:101,代码来源:NetworkFunctions.cs

示例10: SendSingleFtp

        //& IM-3927
        private void SendSingleFtp(FtpPending fp)
        {
            bool succeeded = false;
            if (fp == null) return;
            string destinationFilename = "";
            try
            {
                if (fp.Retry > 1) _Log.Debug("Retry ftp attachmentFiles: " + fp.AttachmentFiles);

                string destinationPath = "";

                if (fp.DestinationPath != null)
                {
                    // Ensure destination path is in Windows format i.e. "\" between folders
                    string validWindowsPath = fp.DestinationPath;
                    validWindowsPath = validWindowsPath.Replace("/","\\");

                    destinationPath = Path.GetDirectoryName(validWindowsPath);
                    if (destinationPath != "" && !destinationPath.StartsWith("C:") && !destinationPath.StartsWith("\\"))		//& IM-4227
                        destinationPath = "\\" + destinationPath;																//& IM-4227

                    destinationFilename = Path.GetFileName(validWindowsPath);
                }

                if (destinationFilename.Contains("YYMMDD_HHMMSS"))
                {
                    string tmp = destinationFilename.Replace("YYMMDD_HHMMSS", DateTime.UtcNow.ToString("yyyyMMdd_HHmmss"));		//# IM-4227
                    destinationFilename = tmp.Replace(":", "");
                }

                if (destinationFilename.EndsWith("YYYYMMDD")) //PP-206
                {
                    string tmp = destinationFilename.Replace("YYYYMMDD", DateTime.UtcNow.ToString("yyyyMMdd"));	//PP-206
                    destinationFilename = tmp.Replace(":", "");
                }

                if (destinationFilename != "")
                {
                    // User has a custom filename they want to use - so just add the appropriate extension from the source report name
                    destinationFilename += Path.GetExtension(fp.AttachmentFiles);		// use extension from report file generated e.g. CSV	//# IM-4227
                }
                else
                {
                    // use the default report name that the report writer assigned when creating the report
                    destinationFilename = Path.GetFileName(fp.AttachmentFiles);
                }

                // Unencrypt username and password	// TODO

                var sftp = new SftpClient(fp.IPAddress, fp.Port, fp.Username, fp.Password); //# PP-223 ---Added Port Number
                sftp.Connect();

                using (var file = File.OpenRead(fp.AttachmentFiles))
                {
                    if (destinationPath != "")
                    {
                        destinationPath = FormatPathForOSTalkingTo(destinationPath, sftp.WorkingDirectory);
                        sftp.ChangeDirectory(destinationPath);
                    }
                    sftp.UploadFile(file, destinationFilename);
                }

                sftp.Disconnect();
                succeeded = true;
            }
            catch (Exception ex)
            {
                var msg = string.Format("Ftp ID={0} file=[{1}] server=[{2}]: error {3} : Stack {4} destination :{5}",
                    fp.ID, Path.GetFileName(fp.AttachmentFiles).Truncate(30), fp.IPAddress, ex.Message, ex.StackTrace, destinationFilename);
                AttentionUtils.Attention(new Guid("63dd8220-d6a8-badd-8158-bed1aa10d130"), msg);
                _Log.Warn(msg);
                succeeded = false;
            }
            //if ftp'ed successfully, save to FtpSent and delete from FtpPending
            if (succeeded)
            {
                DeleteFtpPending(new IDRequest(fp.ID));
                var req = new SaveRequest<FtpSent>();
                var fs = new FtpSent(fp);
                fs.LastRetryAt = fp.DateModified;
                fs.Retry = fp.Retry + 1;
                fs.TimeToSend = DateTime.MaxValue;//never to send again
                req.Item = fs;
                SaveFtpSent(req);

            }
            //if failed, save to FtpFailed and delete from FtpPending
            else
            {
                DeleteFtpPending(new IDRequest(fp.ID));
                var request = new SaveRequest<FtpFailed>();
                var fs = new FtpFailed(fp);
                fs.LastRetryAt = fp.DateModified;
                if (!string.IsNullOrEmpty(fs.DestinationPath) && fs.Retry < _Retries.Length) //TODO check for path valid syntax
                {
                    fs.TimeToSend = DateTime.UtcNow.AddMinutes(_Retries[fs.Retry]);
                    fs.Retry++;
                }
                else
//.........这里部分代码省略.........
开发者ID:ashish-antil,项目名称:Products,代码行数:101,代码来源:ImardaNotification.Extra.cs

示例11: UploadFile

        public bool UploadFile(string localFileName, Action<ulong> uploadCallback, string remotePath = "")
        {
            string remoteFileName = remotePath+System.IO.Path.GetFileName(localFileName);

            using (var sftp = new SftpClient(GenerateConnectionInfo()))
            {
                sftp.Connect();
                //TODO: check if the directory exists!
                sftp.ChangeDirectory(Workingdirectory);
                sftp.ErrorOccurred += ssh_ErrorOccurred;

                using (var file = File.OpenRead(localFileName))
                {
                    try
                    {
                        sftp.UploadFile(file, remoteFileName, uploadCallback);
                    }
                    catch (Exception e)
                    {
                        return false;
                    }
                }

                sftp.Disconnect();
            }
            return true;
        }
开发者ID:emote-project,项目名称:Scenario1,代码行数:27,代码来源:RemoteNAO.cs

示例12: btnFTP_Click

        private void btnFTP_Click(object sender, EventArgs e)
        {
            //// Get the object used to communicate with the server.
            //FtpWebRequest request = (FtpWebRequest)WebRequest.Create("sftp://ftp.s6.exacttarget.com");
            //request.Method = WebRequestMethods.Ftp.UploadFile;

            //// This example assumes the FTP site uses anonymous logon.
            //request.Credentials = new NetworkCredential("6177443", "mD.5.d6T");

            //// Copy the contents of the file to the request stream.
            //StreamReader sourceStream = new StreamReader(@"D:\\DataExtension1List1.txt");
            //byte[] fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());
            //sourceStream.Close();
            //request.ContentLength = fileContents.Length;

            //Stream requestStream = request.GetRequestStream();
            //requestStream.Write(fileContents, 0, fileContents.Length);
            //requestStream.Close();

            //FtpWebResponse response = (FtpWebResponse)request.GetResponse();

            //MessageBox.Show(string.Format("Archivo Subido, Estado {0}", response.StatusDescription), "Mensaje", MessageBoxButtons.OK, MessageBoxIcon.Warning);

            //response.Close();

            const int port = 22;
            const string host = "ftp.s6.exacttarget.com";
            const string username = "6177443";
            const string password = "mD.5.d6T";
            const string workingdirectory = "/Import//";
            const string uploadfile = @"D:\\DataExtension1List1.txt";

            Console.WriteLine("Creating client and connecting");
            using (var client = new SftpClient(host, port, username, password))
            {
                client.Connect();
                Console.WriteLine("Connected to {0}", host);

                client.ChangeDirectory(workingdirectory);
                Console.WriteLine("Changed directory to {0}", workingdirectory);

                //var listDirectory = client.ListDirectory(workingdirectory);
                //Console.WriteLine("Listing directory:");
                //foreach (var fi in listDirectory)
                //{
                //    Console.WriteLine(" - " + fi.Name);
                //}

                using (var fileStream = new FileStream(uploadfile, FileMode.Open))
                {
                    Console.WriteLine("Uploading {0} ({1:N0} bytes)",
                                        uploadfile, fileStream.Length);
                    client.BufferSize = 4 * 1024; // bypass Payload error large files
                    client.UploadFile(fileStream, Path.GetFileName(uploadfile));
                }

                MessageBox.Show("Archivo " + uploadfile + " subido a " + host, "Mensaje", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }
开发者ID:MijailStell,项目名称:Falabella,代码行数:59,代码来源:FrmDataExtension.cs

示例13: Put

        /// <summary>
        /// Upload Files.
        /// </summary>
        /// <returns></returns>
        public Boolean Put()
        {
            Boolean ok = false;

            // Choose Authentication Method
            AuthenticationMethod authenticationMethod;
            if (PrivateKeyPath != null && PrivateKeyPath.Trim().Length > 0)
            {
                authenticationMethod = new PrivateKeyAuthenticationMethod(UserName, new PrivateKeyFile(PrivateKeyPath, PassPhrase));
            }
            else
            {
                authenticationMethod = new PasswordAuthenticationMethod(UserName, Password);
            }

            // Get Connection Info
            ConnectionInfo connectionInfo;
            if (Port > 0)
	        {
                if (Proxy != null && Proxy.Host != null && Proxy.Host.Length > 0)
                {
                    connectionInfo = new ConnectionInfo(Host, Port, UserName,
                                                        (ProxyTypes)Enum.Parse(typeof(ProxyTypes), Proxy.Type.ToString()),
                                                        Proxy.Host, Proxy.Port,
                                                        Proxy.UserName, Proxy.Password,
                                                        authenticationMethod);
                }
                else
                {
                    connectionInfo = new ConnectionInfo(Host, Port, UserName, authenticationMethod);
                }
            }
            else
            {
                connectionInfo = new ConnectionInfo(Host, UserName, authenticationMethod);
            }

            // Uploads
            Boolean fail = false;
            using (SftpClient sftp = new SftpClient(connectionInfo))
            {
                // Connect
                try
                {
                    sftp.Connect();
                }
                catch (Exception xcp)
                {
                    Logger.Log($"SftpClient.Connect failed:{Environment.NewLine}{ToString()}", 
                                xcp, EventLogEntryType.Error);
                    fail = true;
                }
                // Check Connection
                if (!fail && sftp.IsConnected)
                {
                    // Change Directory
                    if (Directory.Length > 0)
                    {
                        sftp.ChangeDirectory(Directory);
                    }
                    
                    foreach (var filePath in FilePaths)
                    {
                        // Upload File
                        using (FileStream file = File.OpenRead(filePath))
                        {
                            try
                            {
                                String path = Directory.Length > 0 
                                            ? string.Format("{0}/{1}", 
                                                            Directory, Path.GetFileName(filePath)) 
                                            : "";

                                Action<UInt64> del = uploadFileCallback;
                                sftp.UploadFile(file, path, del);

                                //uploadFileResult

                                ok = true;

                            }
                            catch (System.ArgumentException xcp)
                            {
                                Logger.Log($"SftpClient.UploadFile failed:{Environment.NewLine}{ToString()}",
                                            xcp, EventLogEntryType.Error);
                                throw;
                            }
                            catch (Exception xcp)
                            {
                                Logger.Log($"SftpClient.UploadFile failed:{Environment.NewLine}{ToString()}", 
                                            xcp, EventLogEntryType.Error);
                                throw;
                            }
                        }
                    }
                    // Disconnect
//.........这里部分代码省略.........
开发者ID:stevedubyo,项目名称:dubftp,代码行数:101,代码来源:Sftp.cs

示例14: UploadSFTP

        public Response UploadSFTP(DataExtensionImport dataExtensionImport)
        {
            var response = new Response { Success = true, Warning = false };
            try
            {
                const int port = 22;
                const string host = "ftp.s6.exacttarget.com";
                const string username = "6177443";
                const string password = "mD.5.d6T";
                const string workingdirectory = "/Import//";

                using (var client = new SftpClient(host, port, username, password))
                {
                    client.Connect();
                    client.ChangeDirectory(workingdirectory);

                    string extension = Path.GetExtension(dataExtensionImport.Ruta);
                    string nombreArchivo = string.Format("{0}{1}", dataExtensionImport.Nombre, extension);
                    using (var fileStream = new FileStream(dataExtensionImport.Ruta, FileMode.Open))
                    {

                        client.BufferSize = 4 * 1024; // bypass Payload error large files
                        client.UploadFile(fileStream, nombreArchivo);
                    }
                }
            }
            catch (Exception ex)
            {
                response.Success = false;
                response.Message = ex.Message;
            }
            return response;
        }
开发者ID:MijailStell,项目名称:Falabella,代码行数:33,代码来源:FileUploadHelper.cs

示例15: sftpConnect

 /// <summary>
 /// This function will connect to the SFTP server for Wells Fargo
 /// </summary>
 private static void sftpConnect()
 {
     client = new Renci.SshNet.SftpClient(sftpHost, sftpPort, sftpUsername, new PrivateKeyFile(new MemoryStream(Encoding.ASCII.GetBytes(sftpKeyFile))));
     try
     {
         client.Connect();
         client.ChangeDirectory(downloadPath);
     }
     catch (Exception e)
     {
         appendToBody(String.Format("Download client threw an exception: {0}", e.Message.ToString()));
         Console.WriteLine(string.Format("exception...{0}", e));
     }
 }
开发者ID:robertmcconnell2007,项目名称:CCCommunications,代码行数:17,代码来源:Program.cs


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