Unable to connect to server when uploading file using FTP - c#

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

Related

Why getting error: System.Net.WebException: Unable to connect to the remote server while upload a file to FTP server using C#? [duplicate]

This question already has answers here:
FtpWebRequest returns error 550 File unavailable
(15 answers)
Upload and download a file to/from FTP server in C#/.NET
(1 answer)
Closed 1 year ago.
While uploading the file to Hostinger.com FTP server folder, I'm getting the following error:
System.Net.WebException: 'Unable to connect to the remote server'
Error occurs on this row:
Stream requestStream = request.GetRequestStream();
Please help me! Thanks!
//FTP Upload
string sourcefilepath;
string ftpurl = "ftp://IP/home/u323320256/domains/razidawakhana.com/public_html";
string ftpusername = "zikria"; // e.g. username
string ftppassword = "Yamankatita1#"; // e.g. password
string PureFileName = new FileInfo(file_name).Name;
String uploadUrl = String.Format("{0}/{1}/{2}", ftpurl, "PDPix", file_name);
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(uploadUrl);
request.Method = WebRequestMethods.Ftp.UploadFile;
request.Credentials = new NetworkCredential(ftpusername, ftppassword);
request.Proxy = null;
request.KeepAlive = true;
request.UseBinary = true;
request.Method = WebRequestMethods.Ftp.UploadFile;
// Copy the contents of the file to the request stream.
StreamReader sourceStream = new StreamReader(_mediaFile.Path);
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);
```

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.

Download file from url and upload into ftp

I have a requirement that I need to download a file from an URL and need to upload that file into ftp.
I followed the below approach.
pdfMemoryStream= new MemoryStream(client.DownloadData("http://res.cloudinary.com/demo/image/upload/sample.jpg"));
FtpUploadString(pdfMemoryStream, "ftp://192.168.1.1/SampleFiles/", "FTPUserName", "Password");
private static string FtpUploadString(MemoryStream memStream, string to_uri, string user_name, string password)
{
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(to_uri);
request.Method = WebRequestMethods.Ftp.UploadFile;
request.Credentials =
new NetworkCredential(user_name, password);
request.UseBinary = true;
byte[] buffer = new byte[memStream.Length];
memStream.Read(buffer, 0, buffer.Length);
memStream.Close();
using (Stream reqStream = request.GetRequestStream())
{
reqStream.Write(buffer, 0, buffer.Length);
}
return string.Empty;
}
I am getting below exception
An unhandled exception of type 'System.Net.WebException' occurred in
System.dll
Additional information: The requested URI is invalid for this FTP
command.
I think your problem is that your url is missing the file name. If I remember correctly you must pass the file name in the URL. So it would look something like this:
"ftp://192.168.1.1/SampleFiles/file.txt"

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

Downloading a file from internet to ASP.NET MVC web application

For a web application I'm currently working on, I want to download a file from internet to my web server.
I can use below code to download the file to the web server's hard drive, what should I set to the destination path to get this working. We are planing to host this site in a shared hosting environment.
using System.Net;
using(var client = new WebClient())
{
client.DownloadFile("http://file.com/file.txt", #"C:\file.txt");
}
I think common way to do it is this:
string appdataFolder = AppDomain.CurrentDomain.GetData("DataDirectory").ToString();
or
string appdataFolder = System.Web.HttpContext.Current.Server.MapPath(#"~/App_Data");
Also notice, that WebClient class implements IDisposable, so you should use dispose or using struct.
And I eager you to read some naming convention for c# (local variables usually start with lower case letter).
You can upload it from your machine to server through ftp request,
string _remoteHost = "ftp://ftp.site.com/htdocs/directory/";
string _remoteUser = "site.com";
string _remotePass = "password";
string sourcePath = #"C:\";
public void uploadFile(string name)
{
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(_remoteHost +name+ ".txt");
request.Method = WebRequestMethods.Ftp.UploadFile;
request.Credentials = new NetworkCredential(_remoteUser, _remotePass);
StreamReader sourceStream = new StreamReader(sourcePath + name+ ".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();
}

Categories

Resources