Using ftp in C# to send a file - c#

I'm trying to send a file using ftp. I have the following code:
string server = "x.x.x.x"; // Just the IP Address
FileStream stream = File.OpenRead(filename);
byte[] buffer = new byte[stream.Length];
WebRequest request = WebRequest.Create("ftp://" + server);
request.Method = WebRequestMethods.Ftp.UploadFile;
request.Credentials = new NetworkCredential(username, password);
Stream reqStream = request.GetRequestStream(); // This line fails
reqStream.Write(buffer, 0, buffer.Length);
reqStream.Close();
But when I run it, I get the following error:
The requested URI is invalid for this FTP command.
Please can anyone tell me why? Am I using this incorrectly?

I think you need to specify the path and filename you're uploading too, so I think it should be either of:
WebRequest request = WebRequest.Create("ftp://" + server + "/");
WebRequest request = WebRequest.Create("ftp://" + server + "/filename.ext");

When I had to use ftp method, I had to set some flags on request object, without it the function did not work:
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftpPath);
request.KeepAlive = true/false;
request.UsePassive = true/false;
request.UseBinary = xxx;
These flags depend on the server, if you have no access to the server then you cannot know what to use here, but you can test and see what works in your configuration.
And file name is probably missing at the end of URI, so that the server knows where to save uploaded file.

Related

c# Upload to ftp with not created directorys on ftp server

This is the path I am trying to upload to the ftp server:
_ftp://ftp-server/products/productxx/versionxx/releasexx/delivery/data.zip
The problem is that the folders "productxx/versionxx/releasexx/delivery/" do not exist on the server.
Can I create them automatically while uploading the .zip file in c#
My coding at the moment is:
FtpWebRequest request =
(FtpWebRequest)WebRequest.Create(pathToFtp);
// Method set to UploadFile
request.Method = WebRequestMethods.Ftp.UploadFile;
// set password and username
request.Credentials = new NetworkCredential(UserName, Password);
// write MemoryStream in ftpStream
using (Stream ftpStream = request.GetRequestStream())
{
memoryStream.CopyTo(ftpStream);
}
I am getting the System.Net.WebException: "Can't connect to FTP: (553) File name not allowed" at "using (Stream ftpStream =request.GetRequestStream())"
but if my pathToFtp is _ftp://ftp-server/products/data.zip it´s working well
One of the request methods available is WebRequestMethods.Ftp.MakeDirectory. You should be able to use that to do what you want.
Something like this (though I've not tested it), should do the trick:
async Task CreateDirectory(string path)
{
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(path);
request.Method = WebRequestMethods.Ftp.MakeDirectory;
using (var response = (FtpWebResponse)(await request.GetResponseAsync()))
{
Console.WriteLine($"Created: {path}");
}
}
It's answered in more detail here How do I create a directory on ftp server using C#?

copy files from local machine to ftp server c [duplicate]

This question already has answers here:
"Requested URI is invalid" during upload with FtpWebRequest
(2 answers)
Closed 8 years ago.
I need to copy some txt files to ftp server from local machine. I used following code. (took from : http://msdn.microsoft.com/en-us/library/ms229715(v=vs.110).aspx)
FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://ftp.xxxx.com/");
request.Method = WebRequestMethods.Ftp.UploadFile;
// This example assumes the FTP site uses anonymous logon.
request.Credentials = new NetworkCredential("username", "paswword");
// Copy the contents of the file to the request stream.
StreamReader sourceStream = new StreamReader(#"E:\log.txt");
byte [] fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());
sourceStream.Close();
request.ContentLength = fileContents.Length;
Stream requestStream = request.GetRequestStream();
requestStream.Write(fileContents, 0, fileContents.Length);
requestStream.Close();
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
Console.WriteLine("Upload File Complete, status {0}", response.StatusDescription);
response.Close();
}
but i cause "The requested URI is invalid for this FTP command" error. How could I solve that???
You missing file name at URI. For example:
FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://ftp.xxxx.com/log.txt");
Take a good look at example you using. Note test.htm?
FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://www.contoso.com/test.htm");

Error while reading response from HttpWebRequest

I am trying to send contents of 1GB text file over the network. I modified the suggested code for basic authentication and kept it as follows :
WRequest = (HttpWebRequest)HttpWebRequest.Create(URL);
WRequest.Credentials = Credentials;
WRequest.PreAuthenticate = true;
WRequest.ContentType = "text/plain";
WRequest.Method = "POST";
WRequest.AllowWriteStreamBuffering = false;
WRequest.Timeout = 10000;
FileStream ReadIn = new FileStream(filename, FileMode.Open, FileAccess.Read);
ReadIn.Seek(0, SeekOrigin.Begin);
WRequest.ContentLength = ReadIn.Length;
Byte[] FileData = new Byte[ReadIn.Length];
int DataRead = 0;
Stream tempStream = WRequest.GetRequestStream();
do
{
DataRead = ReadIn.Read(FileData, 0, 2048);
if (DataRead > 0)
{
tempStream.Write(FileData, 0, DataRead);
Array.Clear(FileData, 0, 2048);
}
} while (DataRead > 0);
// The response
WResponse = (HttpWebResponse)WRequest.GetResponse();
However, now it gives me System.Net.ProtocolViolationException error : "You must write ContentLength bytes to the request stream before calling [Begin]GetResponse". I checked HttpWebRequest.BeginGetRequestResponse ... and found from debugging that the contentlength for WRequest is not -1. What else could be going wrong ? How should I get the response ?
Update :
The code which worked for small files is as followed :
WebRequest request = WebRequest.Create(url);
request.Method = "POST";
request.Credentials = Credentials;
using (StreamReader reader = new StreamReader(filename))
{
postData = reader.ReadToEnd();
}
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
request.ContentType = "text/plain";
request.ContentLength = byteArray.Length;
Stream dataStream = request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
// The response
WebResponse response = request.GetResponse();
Console.WriteLine(((HttpWebResponse)response).StatusDescription);
dataStream = response.GetResponseStream();
using (StreamReader reader = new StreamReader(dataStream))
{
responseFromServer = reader.ReadToEnd();
}
dataStream.Close();
response.Close();
The article you referenced says
If the Microsoft Internet Information Services (IIS) Web server is configured to use Basic authentication, and you must set the HttpWebRequest.AllowWriteStreamBuffering property to false, you must send a HEAD request to pre-authenticate the connection before you send the POST or PUT request.
EDIT - now with more clarification!
To restate the article, if you want to send a large file to a destination which requires basic authentication, you'll need to issue two separate requests. The key here is that you are setting PreAuthenticate = true. Read the statement literally -- by setting the property to true, you are saying that you will authenticate any requests that you make before you actually attempt them! The framework doesn't know how you want to accomplish this pre-authentication, so you need to perform that action yourself, by sending a HEAD request to the destination. Think of the HEAD HTTP method as being a prologue to the actual request - it describes (or requests information about) a particular resource.
So the process goes like this:
Make a HEAD request to http://someurl/aresource containing the credentials you want to use when making future requests from this client to that server for the listed resource
The server will respond (ideally) with "OK - you may proceed. You're authenticated"
The server immediately regrets its' decision to allow the operation as it finds itself saving a very large file :-)
I don't see you making that HEAD request anywhere in the code you posted - if it's not already there, add this at the beginning of your code (snipped from the sample article ref in OP):
//preAuth the request
// You can add logic so that you only pre-authenticate the very first request.
// You should not have to pre-authenticate each request.
WRequest = (HttpWebRequest)HttpWebRequest.Create(URL);
// Set the username and the password.
WRequest.Credentials = new NetworkCredential(user, password);
WRequest.PreAuthenticate = true;
WRequest.UserAgent = "Upload Test";
WRequest.Method = "HEAD";
WRequest.Timeout = 10000;
WResponse = (HttpWebResponse)WRequest.GetResponse();
WResponse.Close();
// Make the real request.

How can I get file from FTP (using C#)?

Now I know how to copy files from one directory to another, this is really simple.
But now I need to do the same with files from FTP server. Can you give me some example how to get file from FTP while changing its name?
Take a look at How to: Download Files with FTP or downloading all files in directory ftp and c#
// Get the object used to communicate with the server.
FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://www.contoso.com/test.htm");
request.Method = WebRequestMethods.Ftp.DownloadFile;
// This example assumes the FTP site uses anonymous logon.
request.Credentials = new NetworkCredential ("anonymous","janeDoe#contoso.com");
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
Stream responseStream = response.GetResponseStream();
StreamReader reader = new StreamReader(responseStream);
Console.WriteLine(reader.ReadToEnd());
Console.WriteLine("Download Complete, status {0}", response.StatusDescription);
reader.Close();
reader.Dispose();
response.Close();
Edit
If you want to rename file on FTP Server take a look at this Stackoverflow question
Easiest way
The most trivial way to download a binary file from an FTP server using .NET framework is using WebClient.DownloadFile.
It takes an URL to the source remote file and a path to the target local file. So you can use a different name for the local file, if you need that.
WebClient client = new WebClient();
client.Credentials = new NetworkCredential("username", "password");
client.DownloadFile(
"ftp://ftp.example.com/remote/path/file.zip", #"C:\local\path\file.zip");
Advanced options
If you need greater control, that WebClient does not offer (like TLS/SSL encryption, ASCII mode, active mode, etc), use FtpWebRequest. Easy way is to just copy an FTP response stream to FileStream using Stream.CopyTo:
FtpWebRequest request =
(FtpWebRequest)WebRequest.Create("ftp://ftp.example.com/remote/path/file.zip");
request.Credentials = new NetworkCredential("username", "password");
request.Method = WebRequestMethods.Ftp.DownloadFile;
using (Stream ftpStream = request.GetResponse().GetResponseStream())
using (Stream fileStream = File.Create(#"C:\local\path\file.zip"))
{
ftpStream.CopyTo(fileStream);
}
Progress monitoring
If you need to monitor a download progress, you have to copy the contents by chunks yourself:
FtpWebRequest request =
(FtpWebRequest)WebRequest.Create("ftp://ftp.example.com/remote/path/file.zip");
request.Credentials = new NetworkCredential("username", "password");
request.Method = WebRequestMethods.Ftp.DownloadFile;
using (Stream ftpStream = request.GetResponse().GetResponseStream())
using (Stream fileStream = File.Create(#"C:\local\path\file.zip"))
{
byte[] buffer = new byte[10240];
int read;
while ((read = ftpStream.Read(buffer, 0, buffer.Length)) > 0)
{
fileStream.Write(buffer, 0, read);
Console.WriteLine("Downloaded {0} bytes", fileStream.Position);
}
}
For GUI progress (WinForms ProgressBar), see:
FtpWebRequest FTP download with ProgressBar
Downloading folder
If you want to download all files from a remote folder, see
C# Download all files and subdirectories through FTP.

C# FTP app uploads to local directory

I've just written a simple FTP console app to upload files on a local server to a remote FTP site. Everything seems to be working fine until it comes to actually transferring the file. For some reason instead of uploading the file to the specified FTP site it stores the entire file locally with no in the Debug folder with no file type and named the same as the ip of the FTP site. I'm thinking that this has something to do with Visual Studio's debugging. Can anybody give me some guidance on this?
Here is the code I'm using to attempt to upload each file in a string array to the FTP site.
private static void Upload(string ftpServer, string userName, string password, string filename)
{
using (var client = new WebClient())
{
client.Credentials = new NetworkCredential(userName, password);
client.UploadFile(ftpServer, "STOR", filename);
}
}
Use this method instead of that one,it worked for me.
//Directory sands for Remote Server Directory ,it must create if dir not exist
FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://serverIP/directory/file");
request.Method = WebRequestMethods.Ftp.UploadFile;
request.Credentials = new NetworkCredential ("username","password");
// Copy the contents of the file to the request stream.
StreamReader sourceStream = new StreamReader("testfile.txt");
byte [] fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());
sourceStream.Close();
request.ContentLength = fileContents.Length;
Stream requestStream = request.GetRequestStream();
requestStream.Write(fileContents, 0, fileContents.Length);
requestStream.Close();
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
response.Close();
source- http://msdn.microsoft.com/en-us/library/ms229715.aspx
Try this way instead: http://msdn.microsoft.com/en-us/library/ms229715.aspx

Categories

Resources