I am using method to create folder on ftp i want get exception if folder already exsists how to make it over write the existing folder
using System; using System.Net;
class Test {
static void Main()
{
WebRequest request = WebRequest.Create("ftp://host.com/directory");
request.Method = WebRequestMethods.Ftp.MakeDirectory;
request.Credentials = new NetworkCredential("user", "pass");
using (var resp = (FtpWebResponse) request.GetResponse())
{
Console.WriteLine(resp.StatusCode);
}
} }
it is "remote server returned error (550) file not found"
Well, "I want to get exception if folder already exists" and "how to make it overwrite the existing folder" are two opposing questions.
At any rate, I just implemented code to do this the other day. Just check if the directory already exists first. And then respond based on that. There's no point in trying to create a directory that already exists.
And if you need to overwrite it somehow, then delete the existing directory before creating the new one.
You can see the code I wrote for this in the article An FtpClient Class and WinForm Control, although it will just overwrite existing content.
You might want to consider some existing ftp libs out there. I've been using this and have had great success with it. It's an FTP client library that provides high-level FTP functionality for the FTPrequest in the .NET Framework 2.0.
It has an API for checking if directory exists and for creating the directory.
Code # http://ftpclient.codeplex.com/
Article # http://www.codeproject.com/KB/IP/FtpClient.aspx
I use this func in solution
private void createFolder(string ftpUName, string ftpPWord)
{
WebRequest ftpRequest = WebRequest.Create("ftp://mrhotro.ad/new_sc");
ftpRequest.Method = WebRequestMethods.Ftp.MakeDirectory;
ftpRequest.Credentials = new NetworkCredential(ftpUName, ftpPWord);
}
You can't overwrite an existing folder... I'm not even sure what benefit that might be.
In short, you need to capture the exception and decide what to do. Either leave it in place (after all, it already exists...) or you'll need to delete the existing folder and try to recreate it.
I don't remember if you can delete a folder that currently contains files.. If you can't, then you will have to delete those as well.
Related
I'm working for a client that has given me access to two specific folders and their subfolders only. The first one used to be our previous working space and now we will switch to the second one.
When I connect to the SFTP using the WinSCP GUI it connects me to the old folder. However, I can change that by clicking on settings and adding the “new” path in the remote path field. The session will then take me to the new default folder/workspace automatically when I connect.
My question is how can I do this using .NET and the respective winscpnet library?
The problem is the root directory of the session is different to remote path.
Example :
Session directory is /C/Document/.
Remote path is /C/Inetpub/ftproot/username/
When I used the following command on terminal:
winscp.com> open sftp://someone:password;fingerprint=something#ipaddress/C/Inetpub/ftproot/username
winscp.com> put some.txt /in
winscp.com> exit
it works fine! Because as we can see, my session directory is /C/Inetpub/ftproot/username/.
Is there a way to set session root path in C#?
Solved: you are right it is a virtual path so /c/Inetpub instead of c/Inetpub
WinSCP .NET assembly does not use the concept of a working directory. It always uses absolute paths.
So if you have your GUI session configured to start in /new/path, use that as an absolute path in WinSCP .NET assembly.
session.PutFiles(#"c:\local\path\*", "/new/path/", false, transferOptions);
the modern way of doing things would be, using Renci.SshNet.
Dont forget to use regular slashes and to quit your session after things are done.
you can create your Session with:
var connectionInfo = new Renci.SshNet.ConnectionInfo(host, username, new PasswordAuthenticationMethod(username, password));
using (var sftp = new SftpClient(connectionInfo))
{
sftp.Connect();
sftp.ChangeDirectory("..");
sftp.ChangeDirectory("C:\Inetpub\ftproot\username\");
}
sftp.Disconnect();
I am trying to implement FTP transfer using FluentFTP in C#. Getting a directory listing is very easy, but I am stuck on downloading files.
I found one article that has an example in its comments here but it won't compile because I cannot find where the class FtpFile comes from.
Does anybody have an example of how tocan I download a file from an ftp server using FluentFTP ?
EDIT: I found some examples here https://github.com/hgupta9/FluentFTP But there is no example on how to actually download a file.
In the this article Free FTP Library there is an example but it does not compile. This is the example
FtpClient ftp = new FtpClient(txtUsername.Text, txtPassword.Text, txtFTPAddress.Text);
FtpListItem[] items = ftp.GetListing();
FtpFile file = new FtpFile(ftp, "8051812.xml"); // THIS does not compile, class FtpFile is unknown
file.Download("c:\\8051812.xml");
file.Name = "8051814.xml";
file.Download("c:\\8051814.xml");
ftp.Disconnect();
EDIT: The solution
The article I found contained an example that set me in the wrong direction.
It seems there was once a Download method but that is gone long ago now.
So the answer was to let that go and use the OpenRead() method to get a stream and than save that stream to a file.
There are now DownloadFile() and UploadFile() methods built into the latest version of FluentFTP.
Example usage from https://github.com/robinrodricks/FluentFTP#example-usage:
// connect to the FTP server
FtpClient client = new FtpClient();
client.Host = "123.123.123.123";
client.Credentials = new NetworkCredential("david", "pass123");
client.Connect();
// upload a file
client.UploadFile(#"C:\MyVideo.mp4", "/htdocs/big.txt");
// rename the uploaded file
client.Rename("/htdocs/big.txt", "/htdocs/big2.txt");
// download the file again
client.DownloadFile(#"C:\MyVideo_2.mp4", "/htdocs/big2.txt");
We have a Windows 2008 R2 web server with FTP over SSL. This app uses .NET 4.5 and when I upload files, the date/time on the file changes to the current date/time on the server. Is there a way to have the uploaded file preserve the original (last modified) date?
Here is what I have:
FtpWebRequest clsRequest = (FtpWebRequest)WebRequest.Create(FTPFilePath);
clsRequest.EnableSsl = true;
clsRequest.UsePassive = true;
clsRequest.Credentials = new NetworkCredential(swwwFTPUser, swwwFTPPassword);
clsRequest.Method = WebRequestMethods.Ftp.UploadFile;
Byte[] bFile = File.ReadAllBytes(LocalFilePath);
Stream clsStream = clsRequest.GetRequestStream();
clsStream.Write(bFile, 0, bFile.Length);
clsStream.Close();
clsStream.Dispose();
clsRequest = null;
There's really no standard way to update timestamp of a remote file over an FTP protocol. That's probably why the FtpWebRequest does not support it.
There are two non-standard ways to update the timestamp. Either a non-standard MFMT command:
MFMT yyyymmddhhmmss path
or a non-standard use of (otherwise standard) MDTM command:
MDTM yyyymmddhhmmss path
But the FtpWebRequest does not allow you to send a custom command either.
See for example How to send arbitrary FTP commands in C#.
So you have to use a 3rd party FTP library.
For example WinSCP .NET assembly preserves a timestamp of an uploaded file by default.
// Setup session options
SessionOptions sessionOptions = new SessionOptions
{
Protocol = Protocol.Ftp,
HostName = "example.com",
UserName = "user",
Password = "mypassword",
};
using (Session session = new Session())
{
// Connect
session.Open(sessionOptions);
// Upload
session.PutFiles(#"c:\toupload\file.txt*", "/home/user/").Check();
}
See a full example.
Note that WinSCP .NET assembly is not a native .NET assembly. It's rather a thin .NET wrapper around a console application.
(I'm the author of WinSCP)
I know that we can assign file attributes:-
//Change the file created time.
File.SetCreationTime(path, dtCreation);
//Change the file modified time.
File.SetLastWriteTime(path, dtModified);
If you can extract the original date before you save it to the server, then you can change file attributes....something like this:-
Sftp sftp = new Sftp();
sftp.Connect(...);
sftp.Login(...);
// upload the file
sftp.PutFile(localFile, remoteFile);
// assign creation and modification time attributes
SftpAttributes attributes = new SftpAttributes();
System.IO.FileInfo info = new System.IO.FileInfo(localFile);
attributes.Created = info.CreationTime;
attributes.Modified = info.LastWriteTime;
// set attributes of the uploaded file
sftp.SetAttributes(remoteFile, attributes);
I hope this points you in the right direction.
This is an older question, but I will add my solution here. I used an approach similar to the solution proposed by #Martin Prikryl, using the MDTM command. His answer shows the DateTime format string as yyyymmddhhmmss which is incorrect since it does not correctly handle the month and 24 hour time format. In this answer I corrected this issue and provided a full solution using C#.
I used the FluentFTP library which handles many other aspects of working with an FTP through C# very well. To set the modified time, this library does not support it but it has an Execute method. Using the FTP command MDTM yyyyMMddHHmmss /path/to/file.txt will set the modified time of the file.
NOTE: in my instance I needed to use the universal time, which may be the case for you.
The code below shows how to connect to the FTP and set the last modified time using the Execute method and sending the MDTM command.
FtpClient client = new FtpClient("ftp-address", "username", "password");
client.Connect();
FtpReply reply = client.Execute($"MDTM {DateTime.UtcNow.ToString("yyyyMMddHHmmss")} /path/to/file.txt");
I've been trying to finish up a web scraper for a website of mine and have hit a stumbling block on the folder creation for image storage
My code looks like this:
//ftpUser and ftpPass are set at the head of the class
FtpWebRequest lrgRequest = (FtpWebRequest) FtpWebRequest.Create("ftp://ftp.mysite.com/httpdocs/images/large/imgFolder");
lrgRequest.Credentials = new NetworkCredential(ftpUser, ftpPass);
lrgRequest.KeepAlive = false;
lrgRequest.Method = WebRequestMethods.Ftp.MakeDirectory;
FtpWebResponse response = (FtpWebResponse) lrgRequest.GetResponse();
Console.WriteLine(response);
When i run this code it gets to the response and throws the error 550 saying the folder isn't found
I've compared my approach to a number of examples and by the standard approach it should work. The ftp address is valid and has been checked and i'm wondering is there an issue with my server that is stopping this or is my C# causing the problem
If anyone needs any more info please just say
As always any help is greatly appreciated
Regards
Barry
Definition of FTP 550:
Requested action not taken. File unavailable (e.g., file not found, no
access).
I'd check you have the appropriate permissions (or you app does) and verfiy that the file does indeed exist.
Since you are getting a response code, I doubt your code above is the cause of the problem. However you could always check the AuthenticationLevel and ImpersonationLevel to see if these provide any useful information.
Whenever I use this code it uploads the jpeg, but the jpegs name is STOR with no extension on the server.
Any idea as to why this happens or how I change the file name when saving from my C# desktop application to my FileZilla FTP Server??
Here is the basic code, the names have been changes to protect the innocent ;)
WebClient client = new WebClient();
client.Credentials = new NetworkCredential("username", "password");
client.BaseAddress = "ftp://mysite.com";
client.UploadFile(WebRequestMethods.Ftp.UploadFile, "C:\mypics\pic1.jpg");
Try
client.UploadFile(remoteName, WebRequestMethods.Ftp.UploadFile , #"C:\mypics\pic1.jpg");
WebRequestMethods.Ftp.UploadFile is a string whose value happens to be STOR so the compiler is assuming your are using the client.UploadFile(remoteName, localName) overload which is why your file is named STOR
#sgmoore answered the question. You need just use method correctly:
client.UploadFile("pic1.jpg", "C:\mypics\pic1.jpg");
first argument is remote file name, second is path to local file.
You can also try some other ftp client implementations in .net (anyway FTP is implemented badly in .NET standard library), I've used ftplib and it's working good.