Im able to connect with my sftp server and I'm sure of it because I get the list of files of my server and it passes correct list. But I cant upload file to a folder in mysftp server. Here is my code:
private static void FileUploadUsingSftp(string SFTPAddress, string SFTPUserName, string SFTPPassword,
string SFTPFilePath, string FileName)
{
Sftp sftp = null;
try
{
sftp = new Sftp( SFTPAddress,SFTPUserName , SFTPPassword);
// Connect Sftp
sftp.Connect();
MessageBox.Show("Connected!");
//Check if im surely connected
//list down files in my sftp server folder u01
ArrayList list;
list = sftp.GetFileList("//u01");
foreach (string item in list)
{
MessageBox.Show(item.ToString());
}
MessageBox.Show(list.Count.ToString());
// upload file
sftp.Put(FileName, "//u01"); -----> **I get exception here**
MessageBox.Show("UPLOADED!");
// Close the Sftp connection
sftp.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
finally
{
if (sftp != null)
{
sftp.Close();
}
}
}
I recieve this exception:
"Exception of type 'Tamir.SharpSsh.jsch.SftpException' was thrown."
at Tamir.SharpSsh.jsch.ChannelSftp.put(String src, String dst, SftpProgressMonitormonitor, Int32 mode)
at Tamir.SharpSsh.Sftp.Put(String fromFilePath, String toFilePath)
I've tried using sftp.Put(FileName,SFTPAddress + "//u01");
Ive tried sftp.Put(FileName,SFTPAddress); And it do work but when I look at my sftp server if the file is there, it isn't.
I've tried sftp.Put(FileName,"//u01"); and it throws the same error.
I must upload my file in a folder in my ftp server and one of the folder is u01.
Can anyone help me out. I don't know what's wrong. I'm sure that i'm connected. and when I tried to upload using filezilla it do work so I'm not restricted in writing to our sftp server.
I believe that you have to enter the full filename in your call to Put.
string strippedFileName = StripPathComponent(FileName);
sftp.Put(FileName,"//u01//" + strippedFileName);
Note that StripPathComponent is not implemented, you will have to implement that as well if needed. It would strip a path component from FileName, i.e. remove C:\...\ or ..\...\.
I was also searching for how to upload a file from local/shared path to SFTP server using this library and finally found the solution. You can use the below code.
string host="ssgty";
string username="usr";
string password="passw";
int port=22;
string fromFile=#"D:\Test.txt";
string toFile=#"/dmon/myfolder/Test.txt";
public string CopyToFTP(string host, string username, string password, int port, string fromFile, string toFile)
{
string error = "";
try
{
Scp scp = new Scp(host, username, password);
scp.Connect(port);
scp.To(fromFile, toFile);
}
catch (Exception ex)
{
error = ex.Message;
}
return error;
}
Related
I'm working on a program in C# which downloads a file from a remote server. I set up the connection (like I did for the upload function) like this:
void execute_scp_download(ScpClient scpclient, string remoteFilePath, string targetPath) {
var downloadFilestream = File.OpenWrite(targetPath);
try {
scpclient.Download(remoteFilePath, downloadFilestream);
scpclient.Disconnect();
} catch (Exception e) {
log_error("download could not be done: " + e);
}
}
scpclient gets created in the calling method where I can successfully write scpclient.Connect() without any problems.
But when I try to download a file it'll throw an exception:
30.07.2020 11:08:02 Error: download could not be done: Renci.SshNet.Common.ScpException: scp: /usr/local/etc/cert.der
at Renci.SshNet.ScpClient.ReadString(Stream stream)
at Renci.SshNet.ScpClient.InternalDownload(IChannelSession channel, Stream input, FileSystemInfo fileSystemInfo)
at Renci.SshNet.ScpClient.Download(String filename, FileInfo fileInfo)
at SMGWUpdateTool.Form1.execute_scp_download(ScpClient scpclient, String remoteFilePath, String targetPath) in C:\bla\myscript.cs Line:226.
(I translated some of the words but none of the exception itself)
I have no clue why this doesn't work. It looks like it is an problem with the target file. The remote server is a BusyBox/Linux while my client is running on Windows 10.
Is there any way to fix this?
I am trying to upload an XML file to SFTP server using SSH.NET. (.NetCore 3.1 / VS 2019 / C#)
The remote folder path to upload the file is "/testin/" which we have been confirmed that we have enough write permission to upload files to this folder.
I am able to connect and authorized to SFTP server on this connection.
However, when I try to upload a file, SSH.net return only "Failure" in the exception message with no other clear details.
I am able to download files with no issue.
By checking the summary details of "Upload" function from SSH.NET as below, it specifies that it would return clear error message for permissions and so on.
I did some search on internet with not much success.
// Summary:
// Uploads stream into remote file.
//
// Parameters:
// input:
// Data input stream.
//
// path:
// Remote file path.
//
// canOverride:
// if set to true then existing file will be overwritten.
//
// uploadCallback:
// The upload callback.
//
// Exceptions:
// T:System.ArgumentNullException:
// input is null.
//
// T:System.ArgumentException:
// path is null or contains only whitespace characters.
//
// T:Renci.SshNet.Common.SshConnectionException:
// Client is not connected.
//
// T:Renci.SshNet.Common.SftpPermissionDeniedException:
// Permission to upload the file was denied by the remote host.
// -or-
// A SSH command was denied by the server.
//
// T:Renci.SshNet.Common.SshException:
// A SSH error where System.Exception.Message is the message from the remote host.
//
// T:System.ObjectDisposedException:
// The method was called after the client was disposed.
//
// Remarks:
// Method calls made by this method to input, may under certain conditions result
// in exceptions thrown by the stream.
public void UploadFile(Stream input, string path, bool canOverride, Action<ulong> uploadCallback = null);
Here is my code:
Any idea?
using (var sftp = new SftpClient(Host, TcpPort, Username, Password))
{
try
{
sftp.Connect();
var localFile = Path.Combine(LocalUploadPath + LocalFilename);
// var path = $"{localFile.Replace(#"\", "/")}";
using (var fs = File.OpenRead(localFile))
{
sftp.UploadFile(fs, RemoteUploadRootPath, true);
}
}
catch (Exception ex)
{
sftp.Disconnect();
throw new Exception($"{ex.Message} {ex.InnerException}"
}
finally
{
sftp.Disconnect();
}
}
I found the issue, it was simple enough, in the upload path, the file name was not specified in the file path. :|
This link may worth to share for SSH.NET with some good examples:
https://csharp.hotexamples.com/examples/Renci.SshNet.Sftp/SftpUploadAsyncResult/Update/php-sftpuploadasyncresult-update-method-examples.html
Here is the updated code that works fine:
using (var sftp = new SftpClient(Host, TcpPort, Username, Password))
{
try
{
sftp.Connect();
var localFile = Path.Combine(LocalUploadPath + LocalFilename);
var remoteFilePath = Path.Combine("/testin/" + LocalFilename);
using (var fs = File.OpenRead(localFile))
{
sftp.UploadFile(fs, remoteFilePath, true);//, UploadCallBack);
}
}
catch (Exception ex)
{
sftp.Disconnect();
throw new Exception($"{ex.Message} {ex.InnerException}");
}
finally
{
sftp.Disconnect();
}
}
In my case, I had sent the path to the ListDirectory method with a leading forward slash.
I am trying to read files from different server, using c# console application, but it gives error - "The specified network name is no longer available".
When I ping the server, i am getting a reply, but when I run the exe file of project that has code to access files from server it shows the mentioned error.
The path I am using is in this format: \\xxx.xxx.xx.x\EEE\EEE\FolderName
The code that access/read files:
public List<string> GetFiles()
{
List<string> filelist = null;
string fileFromPath = help.fileFromPath;
try
{
filelist = Directory.GetFiles(fileFromPath).ToList();
if (filelist.Count == 0)
{
log.Error("No file to be processed.");
}
}
catch (Exception ex)
{
log.Error(ex.Message);
}
return filelist;
}
Where help.fileFromPath has path value and it is stored in app.config
What could be the reason and how could it be fixed?
I'm trying to download a simple xml file and save it to the users local profile. When trying to download (i don't think this has anything to do with the saving location but i'm not 100% sure) i get the following exception on the webclient.
System.InvalidOperationException
My code is as follows;
public void downloadProxy() {
string url = Properties.Settings.Default.url;
string path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "/netsettings/proxies.xml");
try
{
WebClient GrabFile = new WebClient();
GrabFile.DownloadFile(url, path);
}
catch (WebException webEx)
{
if (webEx.Status == WebExceptionStatus.ConnectFailure)
{
Console.WriteLine("Are you behind a firewall? If so, go through the proxy server.");
}
}
}
If you are on a Windows operating system, use a backslash (not a slash) as folder separator:
\netsettings\proxies.xml
I know that this is a common problem facing over, but am getting this this problem with a different scenario.
am going to explain scenario here
I created a two different projects in a solution. The image containing folder that i want to use for save, i-e upload is outside of these above projects but under same solution.
Actually i created virtual directly (My File Server) on IIS server of this folder
here is my code.
private void SaveData()
{
string filename = Path.GetFileName(ImageUpload.PostedFile.FileName);
string servpath = Server.MapPath(ConfigurationManager.AppSettings["TempFolder"]);
ImageUpload.SaveAs(servpath + filename);
string remoteServerPath = ConfigurationManager.AppSettings["ProductImagesPath"] + filename;
try
{
WebClient client = new WebClient();
client.UploadFile(remoteServerPath, servpath + filename);
}
catch (Exception ex)
{
throw ex;
}
objProductsCustom.ProductName = txtProductName.Text;
objProductsCustom.ProductDiscription = txtAddDiscription.Text;
objProductsCustom.ProductPrice = txtPrice.Text;
objProductsCustom.Quantity = txtQuantity.Text;
objProductsCustom.ImagePath = "servpath" + filename;
int productID = objProductsManager.CreatProduct(objProductsCustom);
}
Where on try-catch, I found "The remote server returned an error: (405) Method Allowed." error. I am stuck.
EDIT
This is the remoteserverpath :
http://localhost/ProductImages/untitled.bmp
And this is the file which i am uploading to remoteserverpath:
C:\Documents and Settings\saltaf\My Documents\Visual Studio 2010\Projects \OnlineShoppingSystem\OnlineShoppingSiteAdminPanel\Temp\Images\untitled.bmp
And this is my call:
webclient.UploadFile(http://localhost/ProductImages/untitled.bmp,C:\Documents and Settings\saltaf\My Documents\Visual Studio 2010\Projects\OnlineShoppingSystem\OnlineShoppingSiteAdminPanel\Temp\Images\untitled.bmp)
Have you tried checking the permissions for the folder which you are saving the file into? It's supposed to include the 'IIS_IUSRS' profile there (which should also have the WRITE permission to the target folder).
Hope this helps.