Error when trying to download a file using .net FtpWebRequest class - c#

Error message is:
The server returned an address in response to the PASV command that is different than the address to which the FTP connection was made.
I get this message when I try to call GetResponse() method below...
Please help.
Here is my C# code :
FileStream outputStream = new FileStream(feedXmlPath + "\" +
"testXml", FileMode.Create);
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftpURL + "/" + zipFileName);
request.UseBinary = true;
request.Credentials = new NetworkCredential(userName, password);
request.KeepAlive = false;
request.Method = WebRequestMethods.Ftp.DownloadFile;
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
Stream ftpStream = response.GetResponseStream();
long cl = response.ContentLength;
int bufferSize = 2048;
int readCount;
byte[] buffer = new byte[bufferSize];
readCount = ftpStream.Read(buffer, 0, bufferSize);
while (readCount > 0)
{
outputStream.Write(buffer, 0, readCount);
readCount = ftpStream.Read(buffer, 0, bufferSize);
}
ftpStream.Close();
outputStream.Close();
response.Close();

The use of FTPWebRequest isn't permitted for security reasons if you're using NAT. Check out this post on Connect.
This post on MSDN might be helpful too.

Try toggling the Passive value to see which works:
request.UsePassive = false;
This may depend on the firewall between the Machines (client and server).
I've noticed if I go through our firewall I need it left at True, otherwise it will return the Exception:
The remote server returned an error: (500) Syntax error, command
unrecognized.
However, if I'm behind the firewall (like two machines connecting directly to each other within a data-center) then I need to set it to False, otherwise it will return the Exception:
The server returned an address in response to the PASV command that is different than the address to which the FTP connection was
made.

Related

C# FTP with FtpWebRequest upload fails with "534 Policy requires SSL"

When I try to upload files to an SFTP server it shows an error.
Here is my code:
string fileNameOnly = Path.GetFileName(uploadingFile);
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(HostAddress+ "/test1");
request.Method = WebRequestMethods.Ftp.UploadFile;
request.Credentials = new NetworkCredential(UserId, Password);
StreamReader sourceStream = new StreamReader(#uploadingFile);
byte[] fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());
sourceStream.Close();
request.ContentLength = fileContents.Length;
filesize = ConvertBytesToMegabytes(request.ContentLength);
Console.WriteLine("hello,{0}", filesize);
// Console.WriteLine("hellosss,{0}", request.ContentLength);
Stream requestStream = request.GetRequestStream();
Console.WriteLine("here,{0}", requestStream);
requestStream.Write(fileContents, 0, fileContents.Length);
filesizedownloaded = ConvertBytesToMegabytes(requestStream.Length);
Console.WriteLine("hellosss,{0}", filesizedownloaded);
worker.ReportProgress(Convert.ToInt32((Convert.ToInt32(filesizedownloaded) / filesize) * 100));
requestStream.Close();
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
FilesDetails.SelectedFileContent = "";
Console.WriteLine("Upload File Complete, status {0}", response.StatusDescription);
MessageBox.Show("File Uploaded!", " File");
response.Close();
I get an exception at Stream requestStream = request.GetRequestStream();
The error is:
Remote server returned an error: (534) 534 Policy requires SSL"
Your server requires an encrypted connection.
To enable the encrypted connection, set FtpWebRequest.EnableSsl:
request.EnableSsl = true;
Your code has other problems and it's unnecessarily complicated.
For a clean FTP code for C#, see Upload and download a file to/from FTP server in C#/.NET.

FTP Upload and Download - getting either 227 or 500 error

I want to upload and download a file using FTP. I managed to put together the following code for my upload and download methods. I am stuck at the same place.
If I use:
ftpRequest.UsePassive = false;
FtpWebResponse response = (FtpWebResponse)ftpRequest.GetResponseStream();
It gives me 500 error.
However, if I use just:
FtpWebResponse response = (FtpWebResponse)ftpRequest.GetResponseStream();
I get: The remote server returned an error: 227 Entering Passive Mode.
This is the same behaviour in both download and upload methods. I am able to upload the file using online clients so I know the server is set up fine. I disabled the firewall of my antivirus as some threads suggested but that doesn't work either. Now I have no idea what to do. My upload and download methods are as follows:
My Upload Method
private static void Upload ()
{
FtpWebRequest ftpRequest = (FtpWebRequest)WebRequest.Create("ftp://ftp.myserver.com/");
ftpRequest.Credentials = new NetworkCredential("username", "password");
ftpRequest.Method = WebRequestMethods.Ftp.ListDirectory;
ftpRequest.UsePassive = false;
FtpWebResponse response = (FtpWebResponse)ftpRequest.GetResponse();
StreamReader streamReader = new StreamReader(response.GetResponseStream());
string line = streamReader.ReadLine();
while (!string.IsNullOrEmpty(line))
{
Console.WriteLine(line);
line = streamReader.ReadLine();
}
streamReader.Close();
}
My Download Method
FtpWebRequest reqFTP;
try
{
FileStream outputStream = new FileStream(#"C:\download.csv", FileMode.Create);
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://ftp.myserver.com/upload/myfile.csv"));
reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
reqFTP.UseBinary = true;
reqFTP.UsePassive = false;
reqFTP.KeepAlive = true;
reqFTP.Credentials = new NetworkCredential("username", "password");
FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
Stream ftpStream = response.GetResponseStream();
long cl = response.ContentLength;
int bufferSize = 2048;
int readCount;
byte[] buffer = new byte[bufferSize];
readCount = ftpStream.Read(buffer, 0, bufferSize);
while (readCount > 0)
{
outputStream.Write(buffer, 0, readCount);
readCount = ftpStream.Read(buffer, 0, bufferSize);
}
ftpStream.Close();
outputStream.Close();
response.Close();
}
catch (Exception ex)
{
}
This is actually a perfectly working solution. Works on my buddy's laptop but not mine. Seems to be some antivirus settings.

Unable to connect to server when uploading file using FTP

I am working with mvc 4.5 trying to upload an image using FTP.
My code:
public virtual void Send(HttpPostedFileBase uploadfile, string fileName)
{
Stream streamObj = uploadfile.InputStream;
byte[] buffer = new byte[uploadfile.ContentLength];
streamObj.Read(buffer, 0, buffer.Length);
streamObj.Close();
string ftpurl = String.Format("{0}/{1}/{2}", _remoteHost, _foldersHost, fileName);
var request = FtpWebRequest.Create(ftpurl) as FtpWebRequest;
request.Method = WebRequestMethods.Ftp.UploadFile;
request.UsePassive = false;
request.Credentials = new NetworkCredential(_remoteUser, _remotePass);
request.ContentLength = buffer.Length;
var requestStream = request.GetRequestStream();
requestStream.Write(buffer, 0, buffer.Length);
requestStream.Close();
var response = (FtpWebResponse) request.GetResponse();
if (response != null)
response.Close();
}
The code is working on localhost, I am able to conect to the FTP server and upload the file, but the problem comes once the project is published. I am using SmarterASP to host the site. When I try to upload the image on production, the uploading method gives me an exception, the message says "Unable to connect to the remote server".
Any clue or workaround?
Exception details:
System.Net.FtpWebRequest.GetRequestStream() at AgileResto.Controllers.RestaurantsController.Send(HttpPosted‌​FileBase uploadfile, String fileName) at AgileResto.Controllers.RestaurantsController.UploadFile(Int3‌​2 RestaurantList, HttpPostedFileBase file, HttpPostedFileBase file2)
you need to grant write permission in the server to the folder you are saving the file to

Read FTP server from app Hosted in Azure

I am trying to connect my app to read a document hosted in my FTP server, I am using FileZilla, my app is hosted in Azure. But it seems it cannot connected. I have a public IP, in localhost my app runs fine but when it's online it failed.
This is the code I am using to connect the app with my FTP server.
public static void getExcelFromFTP(string destinationFile)
{
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(#"ftp://100.100.100.0/folder/file.xlsx");
request.KeepAlive = true;
request.UseBinary = true;
request.Credentials = new NetworkCredential(#"username", "password");//FTP Server credentials
request.Method = WebRequestMethods.Ftp.DownloadFile;
Stream reader = request.GetResponse().GetResponseStream();
FileStream fileStream = new FileStream(destinationFile, FileMode.Create);
int bytesRead = 0;
byte[] buffer = new byte[2048];
while (true)
{
bytesRead = reader.Read(buffer, 0, buffer.Length);
if (bytesRead == 0)
break;
fileStream.Write(buffer, 0, bytesRead);
}
fileStream.Close();
}
Can somebody help me out with this issue?
Thanks in advance.
The only thing what I had to it was to make sure that links were written correctly at the moment of attach files to the email.

Uploading a file to a ftp server fails

I have a small C# winform in which I generate some text files and then move them to an ftp server.
When I try to move them to the production server it fails under
The remote server returned an error: (530) Not logged in.
If I log in to the ftp via cmd/ftp with the same ftp address, username and password, everything is ok. I also installed a local ftp server on my machine and tested it to see if perhaps my code is generating the error, but locally it works like a charm, I have the problem only with the production ftp server.
Below is my code to connect and upload the files to the ftp server:
string[] FileName = Directory.GetFiles(outputpath);
foreach (string txtFile in FileName)
{
FileInfo toUpload = new FileInfo(txtFile);
FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://" + tbFTPAddress.Text + #"//" + toUpload.Name);
request.Credentials = new NetworkCredential(tbFTPUserName.Text.Trim(), tbFTPPassword.Text.Trim());
request.Method = WebRequestMethods.Ftp.UploadFile;
Stream ftpStream = request.GetRequestStream();
FileStream file = File.OpenRead(txtFile);
int length = 1024;
byte[] buffer = new byte[length];
int bytesRead = 0;
try
{
do
{
bytesRead = file.Read(buffer, 0, length);
ftpStream.Write(buffer, 0, bytesRead);
}
while (bytesRead != 0);
file.Close();
ftpStream.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error encountered!", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
if (file != null) file.Close();
if (ftpStream != null) ftpStream.Close();
}
}
The error comes at: Stream ftpStream = request.GetRequestStream();
Any ideas?
Thanks!
you have to call GetResponse() at first.
FtpWebRequest request = (FtpWebRequest)FtpWebRequest.Create(uri);
request.Method = WebRequestMethods.Ftp.UploadFile;
request.Credentials = new NetworkCredential(Username, Password);
try
{
//You have to call this or you would be unable to get a stream :)
WebResponse response = fwr.GetResponse();
}
catch (Exception e)
{
throw e;
}
FileStream fs = new FileStream(localfile), FileMode.Open);
byte[] fileContents = new byte[fs.Length];
fs.Read(fileContents, 0, Convert.ToInt32(fs.Length));
fs.Flush();
fs.Close();
//Now you are able to open a Stream
Stream requestStream = request.GetRequestStream();
requestStream.Write(fileContents, 0, fileContents.Length);
requestStream.Close();
request.Abort();
I had this error too. (You do not need to get the response first.) In my case, it was a problem of folder permissions on the FTP server.
Remote in to your FTP server
Navigate to and right-click the folder/subfolder
Select properties
Switch to the Security tab
Click the Edit button
Make sure the IIS user account has write access

Categories

Resources