SFTP文件上传

问题描述:

我创建了使用FTP上传的文件(代码如下),它正常工作。但现在我必须做一个文件上传使用SFTP 请你引导我在VS中使用sftp库。SFTP文件上传

class Program 
{ 
    static void Main(string[] args) 
    { 

     try 
     { 




      string path = ConfigurationManager.AppSettings["filepath"]; 
      string[] files = Directory.GetFiles(path, @"*.xlsx"); 
      string FtpServer = ConfigurationManager.AppSettings["ftpurl"]; 
      string Username = ConfigurationManager.AppSettings["username"]; 
      string Password = ConfigurationManager.AppSettings["password"]; 
      string directory = ConfigurationManager.AppSettings["directoryname"]; 


      if (files != null) 
      { 
       foreach (string file in files) 
       { 

        int port = 22; 
        FileInfo fi = new FileInfo(file); 
        string fileName = fi.Name; 
        string fileurl = path + @"/" + fileName; 
        string ftpFile = FtpServer + @":" + port + @"/" + directory + @"/" + fileName; 
        FtpWebRequest myRequest = (FtpWebRequest)FtpWebRequest.Create(ftpFile); 

        //WebRequest myreq = (WebRequest)WebRequest.Create(ftpFile); 

        //myreq.Credentials = new NetworkCredential(Username, Password); 
        myRequest.Credentials = new NetworkCredential(Username, Password); 
        //WebProxy wb = new WebProxy("http://proxy4.wipro.com:8080"); 
        //wb.Credentials = new NetworkCredential(Username, Password); 
        //myRequest.Proxy = wb; 

        myRequest.Method = WebRequestMethods.Ftp.UploadFile; 
        myRequest.Timeout = 1000000; 
        myRequest.UseBinary = true; 
        myRequest.KeepAlive = true; 


        myRequest.ContentLength = fi.Length; 

        byte[] buffer = new byte[4097]; 
        int bytes = 0; 
        int total_bytes = (int)fi.Length; 
        System.IO.FileStream fs = fi.OpenRead(); 
        System.IO.Stream rs = myRequest.GetRequestStream(); 


        while (total_bytes > 0) 
        { 
         bytes = fs.Read(buffer, 0, buffer.Length); 
         rs.Write(buffer, 0, bytes); 
         total_bytes = total_bytes - bytes; 
        } 

        fs.Close(); 
        rs.Close(); 

        //WebRequest upload = (WebRequest)myreq.GetResponse(); 
        FtpWebResponse uploadResponse = (FtpWebResponse)myRequest.GetResponse(); 
        Console.WriteLine("Upload File Successful"); 
        uploadResponse.Close(); 

       } 
      } 
     } 
     catch (Exception ex) 
     { 
      FTPDirectory.logfile.LogInfo("Error in Uploading file in ftp://ftp.xactlycorp.com" + ex.Message); 
     } 

} 
} 

有一些名为SharpSSH,您可以使用:

http://www.tamirgal.com/blog/page/SharpSSH.aspx

用法示例:

sftp = new Tamir.SharpSsh.Sftp(ipAddress, username, password); 
sftp.Connect(); 
sftp.Get(sourcePath, destinationPath); 
sftp.Close(); 
+1

请勿使用SharpSSH。这是一个死了的项目(自2007年以来没有更新) –

+0

糟糕,你去 - 不使用它 - 但是,如果你搜索“C#SFTP”,你会得到大量简单易用的库,或多或少就像SharpSSH一样。答案的关键在于:搜索是你的朋友。 –

+0

有没有什么办法可以创建文件上传SFTP而不使用任何第三方库? – Sandy777

您还可以使用http://www.chilkatsoft.com/ssh-sftp-dotnet.asp

伊夫用这个有很多的东西,它非常好。