简体   繁体   中英

error: Renci.SshNet.Common.SftpPathNotFoundException: 'No such file' in c#

so I have this code:

public static void UploadSFTPFile(string host, string username,
    string password, string sourcefile, string destinationpath, int port)
    {
        string Ip = "";
        String strHostName = string.Empty;
        IPHostEntry ipEntry = Dns.GetHostEntry(strHostName);
        IPAddress[] addr = ipEntry.AddressList;

        for (int i = 0; i < addr.Length; i++)
        {
            Ip = (addr[i].ToString());
        }
        using (SftpClient client = new SftpClient(host, port, username, password))
        {
            client.Connect();
            client.ChangeDirectory(destinationpath);
            using (FileStream fs = new FileStream(sourcefile, FileMode.Open))
            {
                client.BufferSize = 4 * 1024;
                client.UploadFile(fs, Path.GetFileName(sourcefile));

            }
            client.WriteAllText("C:/Users/Public/Documents/192.168.0.112.json", "jeff");
        }
    }

I use this method to upload files in my sftp server. this works perfectly, but I also try to write something in the file:

 client.WriteAllText("C:/Users/Public/Documents/Test.json", "jeff");

this is where I het the error message:

Renci.SshNet.Common.SftpPathNotFoundException: 'No such file'

what am I doing wrong this is where the file is located and I am admin.

In Windows, the folder delimiter is a backslash "\\" not a slash "/"

Rather use

client.WriteAllText(@"C:\Users\Public\Documents\Test.json", "jeff");
//                  ^---------------------- Notice the @ that will automatically escape the \

It turns out that any of the methods such as ChangeDirectory and UploadFile expect a path relative to the WorkingDirectory property. As a result, I fixed my issue by changing it to

client.ChangeDirectory(@"/other_directory");

Hope that helps someone else

This exception is being thrown due to incorrect path to the sftp.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM