Download file from url and upload into ftp - c#

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"

Related

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

HttpWebRequest Issue to remote server

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.

How do i upload a file to my ftp at weebly.com?

This is what they say about using the ftp:
http://www.ipage.com/controlpanel/FTP.bml
You can build your site using Web authoring tools, and then use an FTP program to upload the Web pages to your iPage account.
To access your account using an FTP client, you need to connect to ftp.newsxpressmedia.com with your FTP username and password.
This is the method i'm trying now:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Net;
namespace ScrollLabelTest
{
class FtpFileUploader
{
static string ftpurl = "ftp://ftp.newsxpressmedia.com";
static string filename = #"c:\temp\test.txt";
static string ftpusername = "newsxpressmediacom";
static string ftppassword = "*****";
static string value;
public static void test()
{
try
{
// Get the object used to communicate with the server.
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftpurl);
request.Method = WebRequestMethods.Ftp.UploadFile;
// This example assumes the FTP site uses anonymous logon.
request.Credentials = new NetworkCredential(ftpusername, ftppassword);
// Copy the contents of the file to the request stream.
StreamReader sourceStream = new StreamReader(#"c:\temp\test.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();
}
catch(Exception err)
{
string t = err.ToString();
}
}
}
}
But i'm getting exception on the line:
Stream requestStream = request.GetRequestStream();
The exception:
The requested URI is invalid for this FTP command
The complete exception error message:
System.Net.WebException was caught
HResult=-2146233079
Message=The requested URI is invalid for this FTP command.
Source=System
StackTrace:
at System.Net.FtpWebRequest.GetRequestStream()
at ScrollLabelTest.FtpFileUploader.test() in e:\test\test\test\FtpFileUploader.cs:line 36
InnerException:
Line 36 is:
Stream requestStream = request.GetRequestStream();
FtpWebRequest request = (FtpWebRequest)FtpWebRequest.Create(
ftpUrl + "/" + Path.GetFileName(fileName));
You need to include the filename.

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**********");
}
}

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