1 / 4
2 / 4
3 / 4
4 / 4

Saturday 13 March 2021

How to upload file on SFTP using Asp.Net C#

SFTP – SSH Secure File Transfer Protocol


SFTP (SSH File Transfer Protocol) is a secure file transfer protocol. It runs over the SSH protocol. It supports the full security and authentication functionality of SSH.





SFTP has pretty much-replaced legacy FTP as a file transfer protocol and is quickly replacing FTP/S. It provides all the functionality offered by these protocols, but more securely and more reliably, with easier configuration. There is basically no reason to use the legacy protocols anymore. 


SFTP also protects against password sniffing and man-in-the-middle attacks. It protects the integrity of the data using encryption and cryptographic hash functions and authenticates both the server and the user.

Start Upload File on SFTP

1) First you need Renci.SshNet.ddl for uploaded files, you can download from www.nuget.org.
2) you need Host, User Name, Password, Port.
3) Add a web form and add design.



<form id="form1" runat="server">

        <div>

            <p><strong>How to upload file on SFTP server using Aps.net C#</strong></p>

            <br />

            <br />

            &nbsp;&nbsp;&nbsp;&nbsp;

            <asp:Button ID="Button1" runat="server" Text="Uplode File To SFTP" OnClick="Button1_Click" />

            <br />

            <br />

            <asp:Label ID="lblresponsemsg" runat="server" Text=""></asp:Label>

        </div>

    </form>


4) Now write C# code like below .




 

protected void Button1_Click(object sender, EventArgs e)

    {

        try

        {

            string SftpPth = "//HOME";

            string SftPHost = "***.***.***.**";//Use Your IP Address

            string SftpUserName = "UserName";

            string SftpPsd = "UserPass@123";

            int SftpPort = 22; //Port 22 is defaulted for SFTP upload


            //Local file address

            string source = "location Of File ";//Upload File Address

            string destination = SftpPth;// If destination address available


            UploadSFTPFile(SftPHost, SftpUserName, SftpPsd, source, destination, SftpPort);

            lblresponsemsg.Text = "File uploaded";


        }

        catch (Exception ex)

        {

            lblresponsemsg.Text = ex.Message.ToString();

        }

    }

    private void UploadSFTPFile(string host, string username, string password, string sourcefile, string destination, int port)

    {

        using (SftpClient client = new SftpClient(host, port, username, password))

        {

            client.Connect();

            client.ChangeDirectory(destination);

            using (FileStream fs = new FileStream(sourcefile, FileMode.Open))

            {

                client.BufferSize = 4 * 1024;

                client.UploadFile(fs, Path.GetFileName(sourcefile));

            }

        }

    }

No comments:

Post a Comment

If you have any doubts please let me know