C#SFTP上传文件

Eya*_*yal 12 c#

我试图将文件上传到Linux服务器,但我收到一个错误说:" Unable to connect to the remote server".我不知道我的代码是错还是连接被服务器阻止 - 我可以用FileZilla连接服务器.

我的代码:

    const string UserName = "userName";
    const string Password = "password";
    const string ServerIp = "11.22.333.444/";

    public bool UploadFile(HttpPostedFileBase file)
    {
        string fileName = file.FileName;

        var serverUri = new Uri("ftp://" + ServerIp + fileName);


        // the serverUri should start with the ftp:// scheme.
        if (serverUri.Scheme != Uri.UriSchemeFtp)
            return false;

        try
        {
            // get the object used to communicate with the server.
            var request = (FtpWebRequest)WebRequest.Create(serverUri);

            request.EnableSsl = true;
            request.UsePassive = true;
            request.UseBinary = true;
            request.Credentials = new NetworkCredential(UserName, Password);
            request.Method = WebRequestMethods.Ftp.UploadFile;

            // read file into byte array
            var sourceStream = new StreamReader(file.InputStream);
            byte[] fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());
            sourceStream.Close();
            request.ContentLength = fileContents.Length;

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

            var response = (FtpWebResponse)request.GetResponse();
            Console.WriteLine("Response status: {0}", response.StatusDescription);
        }
        catch (Exception exc)
        {
            throw exc;
        }
        return true;
    }
Run Code Online (Sandbox Code Playgroud)

Tre*_*man 26

使用C#上传SFTP文件

我找到的最好的库/ NuGet包是Renci的SSH.NET.打开Nuget Package Manager并将其安装到您的项目中.

上传可以使用存储的文件或byte[]文件完成.


上传byte []文件

    // you could pass the host, port, usr, and pass as parameters
    public void FileUploadSFTP()
    {
        var host = "whateverthehostis.com";
        var port = 22;
        var username = "username";
        var password = "passw0rd";

        // http://stackoverflow.com/questions/18757097/writing-data-into-csv-file/39535867#39535867
        byte[] csvFile = DownloadCSV(); // Function returns byte[] csv file

        using (var client = new SftpClient(host, port, username, password))
        {
            client.Connect();
            if (client.IsConnected)
            {
                Debug.WriteLine("I'm connected to the client");

                using (var ms = new MemoryStream(csvFile))
                {
                    client.BufferSize = (uint)ms.Length; // bypass Payload error large files
                    client.UploadFile(ms, GetListFileName());
                }
            }
            else
            {
                Debug.WriteLine("I couldn't connect");
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

从存储的文件上传

这是我用来作为资源让我入门的引用:http://blog.deltacode.be/2012/01/05/uploading-a-file-using-sftp-in-c-sharp/ 这是为...上传文件.

    // you could pass the host, port, usr, pass, and uploadFile as parameters
    public void FileUploadSFTP()
    {
        var host = "whateverthehostis.com";
        var port = 22;
        var username = "username";
        var password = "passw0rd";

        // path for file you want to upload
        var uploadFile = @"c:yourfilegoeshere.txt"; 

        using (var client = new SftpClient(host, port, username, password))
        {
            client.Connect();
            if (client.IsConnected)
            {
                Debug.WriteLine("I'm connected to the client");

                using (var fileStream = new FileStream(uploadFile, FileMode.Open))
                {

                    client.BufferSize = 4 * 1024; // bypass Payload error large files
                    client.UploadFile(fileStream, Path.GetFileName(uploadFile));
                }
            }
            else
            {
                Debug.WriteLine("I couldn't connect");
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)


希望这对于尝试使用C#中的SFTP上传文件的任何人都有帮助.


Mic*_*ter 8

您在这里尝试做的是建立一个不是 SFTP 连接的 FTPS 连接。该EnableSsl选项仅激活基于 TLS 的 FTP(即 FTPS)。它使用端口 21 连接到服务器。

如果您真的在 FileZilla 中激活了 SFTP,则必须使用端口 22 上的 SSH 连接来连接到服务器(SFTP = SSH 文件传输协议)。获得它的最简单方法应该是使用SharpSSH

你也可以看看这个问题