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
Related
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.
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(HttpPostedFileBase uploadfile, String fileName) at AgileResto.Controllers.RestaurantsController.UploadFile(Int32 RestaurantList, HttpPostedFileBase file, HttpPostedFileBase file2)
you need to grant write permission in the server to the folder you are saving the file to
I'm trying to upload files to a remote server (windows server 2008 R2) from my asp.net 1.1 (C#) Windows application (I know.. It's really old, sadly, that's what we have). When I try to upload, it's giving me an error: "The remote server returned an error: (404) Not Found.".
Here's the code I'm using:
Any ideas?
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(uploadUrl);
req.Credentials = new NetworkCredential(uName,pwd);
req.Method = "PUT";
req.AllowWriteStreamBuffering = true;
// Retrieve request stream
Stream reqStream = req.GetRequestStream();
// Open the local file
FileStream rdr = new FileStream(txt_filename.Text, FileMode.Open);
// Allocate byte buffer to hold file contents
byte[] inData = new byte[4096];
// loop through the local file reading each data block
// and writing to the request stream buffer
int bytesRead = rdr.Read(inData, 0, inData.Length);
while (bytesRead > 0)
{
reqStream.Write(inData, 0, bytesRead);
bytesRead = rdr.Read(inData, 0, inData.Length);
}
rdr.Close();
reqStream.Close();
req.GetResponse();
The uploadUrl is like this: http://10.x.x.x./FolderName/Filename
Please use "POST" method instead of "PUT" and I guess it will work.
Edit:
Check the code below, it will help you.
public void UploadFile()
{
string fileUrl = #"enter file url here";
string parameters = #"image=" + Convert.ToBase64String(File.ReadAllBytes(fileUrl));
WebRequest req = WebRequest.Create(new Uri("location url here"));
req.ContentType = "application/x-www-form-urlencoded";
req.Method = "POST";
byte[] bytes = Encoding.ASCII.GetBytes(parameters);
try
{
req.ContentLength = bytes.Length;
Stream s = req.GetRequestStream();
s.Write(bytes, 0, bytes.Length);
s.Close();
}
catch (WebException ex)
{
throw ex; //Request exception.
}
try
{
WebResponse res = req.GetResponse();
StreamReader sr = new StreamReader(req.GetResponseStream());
}
catch (WebException ex)
{
throw ex; //Response exception.
}
}
Enter fileUrl variable correctly and take care of uri while creating WebRequest instance, write the url of the locating folder.
I found a number of similar articles here but did not manage to solve my problem still.
I am trying to upload a text file to an ftp server. I used a number of methods and all of them i get same error : "Can not connect to remote server"
Method1 :
filename is the full path where the file is located
private string Upload(string ftpServer, string userName, string password, string filename)
{
string reply = "Success";
try
{
using (System.Net.WebClient client = new System.Net.WebClient()) //System.Net.WebClient client = new System.Net.WebClient()
{
client.Credentials = new System.Net.NetworkCredential(userName, password);
client.Proxy = new WebProxy();
FileInfo fi = new FileInfo(filename);
client.UploadFile(ftpServer + "//" + fi.Name, "STOR", filename);
}
}
catch (Exception ex)
{
reply = ex.Message;
}
return reply;
}
Method2:
filename = "D:\folder\file.txt"
public static void uploadFileUsingFTP(string filename)
{
FileInfo fileInf = new FileInfo(filename);
string uri = "ftp://" + serverIP + "/" + fileInf.Name;
FtpWebRequest reqFTP;
// Create FtpWebRequest object from the Uri provided
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
reqFTP.Proxy = null;
// Provide the WebPermission Credintials
reqFTP.Credentials = new NetworkCredential(user, pass);
// By default KeepAlive is true, where the control connection is not closed
// after a command is executed.
reqFTP.KeepAlive = false;
// Specify the command to be executed.
reqFTP.Method = WebRequestMethods.Ftp.UploadFile;
// Specify the data transfer type.
reqFTP.UseBinary = true;
// Notify the server about the size of the uploaded file
FileStream fs = File.OpenRead(filename);
reqFTP.ContentLength = fileInf.Length;
// The buffer size is set to 2kb
int buffLength = Convert.ToInt32(fs.Length);
byte[] buff = new byte[buffLength];
int contentLen;
try
{
// Stream to which the file to be upload is written
Stream strm = reqFTP.GetRequestStream();
// Read from the file stream 2kb at a time
contentLen = fs.Read(buff, 0, buffLength);
// Till Stream content ends
while (contentLen != 0)
{
// Write Content from the file stream to the FTP Upload Stream
strm.Write(buff, 0, contentLen);
contentLen = fs.Read(buff, 0, buffLength);
}
// Close the file stream and the Request Stream
strm.Close();
fs.Close();
}
catch (Exception ex)
{
string s = ex.Message;
}
}
Method3:
public static void Sample(string filename)
{
// Get the object used to communicate with the server.
FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://serverip/"); //test.htm
request.Method = WebRequestMethods.Ftp.UploadFile;
// This example assumes the FTP site uses anonymous logon.
request.Credentials = new NetworkCredential (user,passs);
try
{
// Copy the contents of the file to the request stream.
StreamReader sourceStream = new StreamReader(filename);
byte[] fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());
sourceStream.Close();
request.ContentLength = fileContents.Length;
request.Proxy = null;
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();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
Console.ReadLine();
}
Using each of them results in the same problem and yes i am able to connect to the ftp by using filezilla and also transfer files.
I know that i must be missing something very stupid but it is taking me so much time.
Any suggestion will be appreaciated.
Connection problems can be a nuisance to sort out. A tool like WireShark can be a big help in tracking down problems, e.g. when trying active vs. passive mode FTP transfers.
I've been using the following code with good results:
bool result = false;
long length = 0;
// Set up the FTP upload.
// The URI for the request specifies the protocol, the server and the filename.
FtpWebRequest ftpRequest = (FtpWebRequest)WebRequest.Create("ftp://" + ftpServerUrl + "/" + targetFilename);
ftpRequest.EnableSsl = false;
ftpRequest.KeepAlive = true;
ftpRequest.ReadWriteTimeout = ftpTimeout; // To perform an individual read or write.
ftpRequest.Timeout = ftpTimeout; // To establish a connection or start an operation.
ftpRequest.Credentials = new NetworkCredential(ftpUsername, ftpPassword);
ftpRequest.Method = WebRequestMethods.Ftp.UploadFile;
ftpRequest.UseBinary = true;
ftpRequest.UsePassive = true;
// Upload the file.
using (FileStream fileStream = File.OpenRead(filename))
{
using (Stream ftpStream = ftpRequest.GetRequestStream())
{
fileStream.CopyTo(ftpStream);
length = fileStream.Length;
ftpStream.Close();
}
FtpWebResponse ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();
if (ftpResponse.StatusCode == FtpStatusCode.ClosingData)
result = true;
else
throw new Exception(ftpResponse.StatusDescription + " (" + ftpResponse.StatusCode + ")");
ftpResponse.Close();
}
Have already replied in another thread, however repeating here as well. I faced the same issue, here was my solution.
request.Credentials = new NetworkCredential(
usernameVariable.Normalize(),passwordVariable.Normalize(),domainVariable.Normalize());
Details can be found here
Hope it helps someone.
Add the following in your web.config to have your FtpWebRequest use the default proxy
<defaultProxy enabled="true" useDefaultCredentials="true">
</defaultProxy>
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.