Suresh
Suresh

Reputation: 1

PuTTY in C# for file transfer

Can any one help me with a code snippet in C# for transferring a file on my local machine to a remote server using PSCP (PuTTY) transfer methodology? I would really appreciate the help. Thanks

Upvotes: 0

Views: 8798

Answers (2)

Chaitanya
Chaitanya

Reputation: 33

Using SFTP and SCP supported clients with .NET Libraries might be the best option. But here is a simple way to use PSCP:

Process cmd = new Process();
cmd.StartInfo.FileName = @"C:\PuTTY\pscp.exe";
cmd.StartInfo.UseShellExecute = false;
cmd.StartInfo.RedirectStandardInput = true;
cmd.StartInfo.RedirectStandardOutput = true;
string argument = @"-pw pass C:\testfile.txt [email protected]:/home/usr";
cmd.StartInfo.Arguments = argument;

cmd.Start();
cmd.StandardInput.WriteLine("exit");
string output = cmd.StandardOutput.ReadToEnd();

Upvotes: 0

Panagiotis Kanavos
Panagiotis Kanavos

Reputation: 131189

You can use a library that support SCP like SSHNet or WinSCP. Both provide samples and tests that demonstrate how they work.

With SSH.Net you can upload a file using this code (from the test files):

using (var scp = new ScpClient(host, username, password))
{
    scp.Connect();
    scp.Upload(new FileInfo(filename), Path.GetFileName(filename));
    scp.Disconnect();

}

With the WinSCP library the code looks like this (from the samples):

SessionOptions sessionOptions = new SessionOptions {
            Protocol = Protocol.Sftp,
            HostName = "example.com",
            UserName = "user",
            Password = "mypassword",
            SshHostKey = "ssh-rsa 1024 xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx"
};

using (Session session = new Session())
{
    // Connect
    session.Open(sessionOptions);

    // Upload files
    TransferOptions transferOptions = new TransferOptions();
    transferOptions.TransferMode = TransferMode.Binary;

    TransferOperationResult transferResult;
    transferResult = session.PutFiles(@"d:\toupload\*", "/home/user/", false, transferOptions);

    // Throw on any error
    transferResult.Check();

}

Upvotes: 3

Related Questions