This project is read-only.

Help with Uploading a string to SFTP

Aug 17, 2011 at 6:17 PM

Hello,

I want to create a string and send it to a sftp server. The reason is I don't want to create a file for security issues. I have tried some of the file examples with no luck. Any help would be appreciated.

Thanks

Robert

Code I tried: [With this code I get the SshPermissionDeniedException Error]

 

string xpath = "/export/test.txt";

string data = "This is a test string to sent";

using (var sftp = new SftpClient (host,username,xkey))

try 

 

{

     

using (var sr = sftp.OpenRead(data))

 
 

     {

 

          sftp.UploadFile(sr, xpath);

 

 

 

     }

 

}

 

catch(SftpPermissionDeniedException)
 

{

   exceptionOccured =

true;

}

 

sftp.Disconnect();

 

System.Windows.Forms.MessageBox .Show(exceptionOccured.ToString());

}

{

sftp.Connect();

 

var exceptionOccured = false;
 

Aug 18, 2011 at 3:02 AM

Hi,

 

You can try this:

            using (var sftp = new SftpClient(connectionInfo))
            {
                sftp.Connect();
                using (var sw = sftp.CreateText("test1.txt"))
                {
                    sw.WriteLine("This is a test string to sent");
                }
                sftp.Disconnect();
            }

And it should do the trick.

The only thing I just tried it myself and it inserts few extra characters for some reason, so I will check it now, may be it only in my development version, but if it happens to you please let me know.

 

Hope it helps,

Oleg

Aug 18, 2011 at 2:28 PM
Edited Aug 18, 2011 at 2:47 PM

Here is another example that you can use, which works without corrupting with extra bytes:

 

            using (var sftp = new SftpClient(connectionInfo))
            {
                sftp.Connect();
                using (var s = sftp.OpenWrite("test.txt"))
                {
                    var data = Encoding.ASCII.GetBytes("ABCDEFG");
                    s.Write(data, 0, data.Length);
                }
                sftp.Disconnect();
            }

You can also use a previous method but then you just need to specify to use ASCII instead of default UTF8.

                using (var sw = sftp.CreateText("test1.txt", Encoding.ASCII))
                {
                    sw.WriteLine("This is a test string to sent");
                }

Thanks,

Oleg