c# FTP to FileZilla Server file name save issue - c#

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.

Related

loading a file from http to a local filepath temporarily using c# webclient

I want to save a file from a http link to the local drive just temporarily in order to access it, this one is working so far and I'm getting the data but a need to write this data to a local file, for example to C:\Windows\temp\test.text, this file should be deleted afterwards.
WebClient client = new WebClient();
string url = "http://www.example.com/test.text";
var file = client.DownloadData(url);
could any one help me on this, thank you!
You cannot write a file on client machine due to security, Any program executing in the browser executes within the browser sandbox and has access to limited features like printer, cookies, etc.
You can write the data to file as a Response object to the client's browser. The Client has the choice of whether to save it or not to his machine.

Download files using FluentFTP

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");

C# - Download files from FTP which have higher last-modified date

I have an FTP server with some files. I have the same files in in a local directory (in C:\).
When I'll run the program, I'd like it searches all files in the FTP server that have a last-modified timestamp later than the same file (equal name) in local directory and download all files founded.
Can someone give me a help or a tip, please? I'll appreciate all answers!
Unfortunately, there's no really reliable and efficient way to retrieve timestamps using features offered by the .NET framework, as it does not support the FTP MLSD command. The MLSD command provides listing of remote directory in a standardized machine-readable format. The command and the format is standardized by the RFC 3659.
Alternatives you can use that are supported by the .NET framework:
the ListDirectoryDetails method (the FTP LIST command) to retrieve details of all files in a directory and then you deal with FTP server specific format of the details (*nix format similar to ls *nix command is the most common, drawback is that the format may change over time, as for newer files "May 8 17:48" format is used and for older files "Oct 18 2009" format is used).
Examples:
DOS/Windows format: C# class to parse WebRequestMethods.Ftp.ListDirectoryDetails FTP response
*nix format: Parsing FtpWebRequest ListDirectoryDetails line
the GetDateTimestamp method (an FTP MDTM command) to individually retrieve timestamps for each file. An advantage is that the response is standardized by the RFC 3659 to YYYYMMDDHHMMSS[.sss]. A disadvantage is that you have to send a separate request for each file, what can be quite inefficient.
const string uri = "ftp://example.com/remote/path/file.txt";
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(uri);
request.Method = WebRequestMethods.Ftp.GetDateTimestamp;
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
Console.WriteLine("{0} {1}", uri, response.LastModified);
Alternatively you can use a 3rd party FTP client implementation that supports the modern MLSD command.
For example the WinSCP .NET assembly supports that.
You can use the Session.ListDirectory or the Session.EnumerateRemoteFiles methods and read the RemoteFileInfo.LastWriteTime of the files in returned collection.
Or even easier, you can use the Session.SynchronizeDirectories to have the library automatically download (synchronize) the modified files:
// Setup session options
SessionOptions sessionOptions = new SessionOptions
{
Protocol = Protocol.Ftp,
HostName = "ftp.example.com",
UserName = "user",
Password = "mypassword",
};
using (Session session = new Session())
{
// Connect
session.Open(sessionOptions);
// Synchronize files
var localPath = #"d:\www";
var remotePath = "/home/martin/public_html";
session.SynchronizeDirectories(
SynchronizationMode.Local, localPath, remotePath, false).Check();
}
WinSCP GUI can generate a code template for you.
(I'm the author of WinSCP)
List all files : https://msdn.microsoft.com/en-us/library/ms229716(v=vs.110).aspx
Read date : https://msdn.microsoft.com/en-us/library/system.net.ftpwebresponse.lastmodified(v=vs.110).aspx

.NET FTP Upload file and preserve original date time

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");

is this possible to create subdirectory in FTP using ftp.MakeDirectory?

I have to create this query to get some answer before i change my code.Pardon me if this question is doesn't make sense to you guys.
Scenario 1:
string path :ftp://1.1.1.1/mpg/test";
FtpWebRequest requestDir = (FtpWebRequest)FtpWebRequest.Create(new Uri(path));
requestDir.Credentials = new NetworkCredential("sh","se");
requestDir.Method = WebRequestMethods.Ftp.MakeDirectory;
Using the same code to create the directory structure to connect my local Filezilla ftp server to do the job---Works Fine.
Scenario 2:
Used the above code to connect the remote ftp server to do the same job throws exception : Error 550 no file found or no Access.
Question 1 : I have a full permission to read/write for the folder,if its not a permission issue,what else i have to keep it in mind to look for it ?
Question 2: If i modified my code like
step1: Make"mpg" direcotry first
step2: make"test" directory after that,works fine
is that mean FTP.Makedirectory won't support to create a subdirectory in the main dir ?
If that's the case how it created in my local ftp server ?
Any help appreciated.
Thanks in Advance.
I dont know why exactly, but some ftp servers response differently. I know because this scenario exactly happened to me while developing dropf. If you are using Filezilla ftp server, create with subdirectories working, but not on IIS ftp server.
So i suggest you to write one method for creating directory, method takes one parameter ant it will be full path, in your scenario (mpg/test), and split it by '/' and create one by one every directory. This way it works on Filezilla and IIS Ftp and some other ftp services.

Categories