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

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.

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

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

Upload a file to an FTP server from a string or stream

I'm trying to create a file on an FTP server, but all I have is either a string or a stream of the data and the filename it should be created with. Is there a way to create the file on the server (I don't have permission to create local files) from a stream or string?
string location = "ftp://xxx.xxx.xxx.xxx:21/TestLocation/Test.csv";
WebRequest ftpRequest = WebRequest.Create(location);
ftpRequest.Method = WebRequestMethods.Ftp.UploadFile;
ftpRequest.Credentials = new NetworkCredential(userName, password);
string data = csv.getData();
MemoryStream stream = csv.getStream();
//Magic
using (var response = (FtpWebResponse)ftpRequest.GetResponse()) { }
Just copy your stream to the FTP request stream:
Stream requestStream = ftpRequest.GetRequestStream();
stream.CopyTo(requestStream);
requestStream.Close();
For a string (assuming the contents is a text):
byte[] bytes = Encoding.UTF8.GetBytes(data);
using (Stream requestStream = request.GetRequestStream())
{
requestStream.Write(bytes, 0, bytes.Length);
}
Or even better use the StreamWriter:
using (Stream requestStream = request.GetRequestStream())
using (StreamWriter writer = new StreamWriter(requestStream, Encoding.UTF8))
{
writer.Write(data);
}
If the contents is a text, you should use the text mode:
request.UseBinary = false;
i make this for send a xml file to a FTP. It works fine. I thinks is what you need.
FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://XXXXXXXXXX//" + filename);
request.Method = WebRequestMethods.Ftp.UploadFile;
request.Credentials = new NetworkCredential("user", "pwd");
request.UsePassive = true;
request.UseBinary = true;
request.KeepAlive = true;
StreamReader sourceStream = new StreamReader(file);
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();
Regards!

System.Net.WebException: The remote server returned an error: (530) Not logged in

I have the same issue as in this question: using ftpWebRequest with an error: the remote server returned error 530 not logged in
I have tried the solutions there, but I can't get past it.
// Get the object used to communicate with the server.
FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://<ftp-ip>/uploadFTP.txt");
request.Method = WebRequestMethods.Ftp.UploadFile;
request.UsePassive = false;
request.EnableSsl = true;
// This example assumes the FTP site uses anonymous logon.
request.Credentials = new NetworkCredential(<username>, <password>);
request.Timeout = -1;
// Copy the contents of the file to the request stream.
StreamReader sourceStream = new StreamReader(<file to be upload>);
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();
Where could I possibly be going wrong ?
I removed request.timeout = -1. And, also UsePassive and EnableSsl, now it is working fine. Thanks.
I am not sure what the problem was but this is the final working code:
FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://<ip>/<file_name>");
request.Method = WebRequestMethods.Ftp.UploadFile;
// This example assumes the FTP site uses anonymous logon.
request.Credentials = new NetworkCredential("username", "password");
// Copy the contents of the file to the request stream.
StreamReader sourceStream = new StreamReader("<file_name>");
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();

C# Ftp upload binary file wont upload

Trying to Find a file and upload it to ftp server, I think i have everything correct but it doesnt upload anything
string filepath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
DirectoryInfo d = new DirectoryInfo(filepath);
List<String> allDatfiles = Directory
.GetFiles(filepath, "data.dat", SearchOption.AllDirectories).ToList();
foreach (string file in allDatfiles)
{
FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://www.test.com/Holder");
request.Method = WebRequestMethods.Ftp.UploadFile;
request.Credentials = new NetworkCredential("User", "Pass");
request.UseBinary = true;
request.UsePassive = true;
byte[] data = File.ReadAllBytes(file); // Think the problem is with file
request.ContentLength = data.Length;
Stream stream = request.GetRequestStream();
stream.Write(data, 0, data.Length);
stream.Close();
}
Also tried putting in the file location as a string with #"C...
I receive no errors, and no file shows up after the upload
Did you check the user permission on server.. can user write to
directory?
if you use linux server this will help you to fix file path issue.
private static void UploadFile(string dir, Uri target, string fileName, string username, string password, string finilizingDir, string startupPath, string logFileDirectoryName)
{
try
{
// Get the object used to communicate with the server.
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(target);
request.Proxy = null;
request.Method = WebRequestMethods.Ftp.UploadFile;
// logon.
request.Credentials = new NetworkCredential(username, password);
// Copy the contents of the file to the request stream.
StreamReader sourceStream = new StreamReader(dir + "\\" + fileName);
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();
if (response.StatusCode == FtpStatusCode.ClosingData)
{
Console.WriteLine(" --> Status Code is :" + response.StatusCode);
}
Console.WriteLine(" --> Upload File Complete With Status Description :" + response.StatusDescription);
response.Close();
}
catch (Exception ex)
{
Console.WriteLine("*** Error Occurred while uploading file :" + fileName + " System Says :" + ex.Message + " **********END OF ERROR**********");
}
}

Categories

Resources