I am using the following code to learn how to load files with FTP. How do I set the path or folder into which my file will be uploaded ?
using System;
using System.IO;
using System.Net;
using System.Text;
namespace Examples.System.Net
{
public class WebRequestGetExample
{
public static void Main ()
{
// Get the object used to communicate with the server.
FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://www.contoso.com/test.htm");
request.Method = WebRequestMethods.Ftp.UploadFile;
// This example assumes the FTP site uses anonymous logon.
request.Credentials = new NetworkCredential ("anonymous","janeDoe#contoso.com");
// Copy the contents of the file to the request stream.
StreamReader sourceStream = new StreamReader("testfile.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();
}
}
}
}
The folder is part of the URL you set when you create request: "ftp://www.contoso.com/test.htm". If you use "ftp://www.contoso.com/wibble/test.htm" then the file will be uploaded to a folder named wibble.
You may need to first use a request with Method = WebRequestMethods.Ftp.MakeDirectory to make the wibble folder if it doesn't already exist.
Related
I am using mvc I am trying to save a file on another folder i.e on another server.
But earlier i was using an approach of creating two different solution and was saving the file using web request.
i was sending the request from one solution and was geeting it on another solution.
here is my code
byte[] bytes;
var pic = System.Web.HttpContext.Current.Request.Files["ImagePath"];
/*Creating the WebRequest object using the URL of SaveFile.aspx.*/
System.Net.HttpWebRequest webRequest =
(System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create
("http://localhost:13492/Home/SaveImage");
webRequest.Method = "POST";
webRequest.KeepAlive = false;
/*Assigning the content type from the FileUpload control.*/
webRequest.ContentType = pic.ContentType ;
/*Creating the Header object.*/
System.Net.WebHeaderCollection headers = new System.Net.WebHeaderCollection();
headers.Add("FileName", pic.FileName);
/*Adding the header to the WebRequest object.*/
webRequest.Headers = headers;
/* Convert File Into byte array */
using (var stream = new MemoryStream())
{
pic.InputStream.CopyTo(stream);
bytes = stream.ToArray();
}
/*Getting the request stream by making use of the GetRequestStream method of WebRequest object.*/
using (System.IO.Stream stream = webRequest.GetRequestStream())//Filling request stream with image stream.
{
/*Writing the FileUpload content to the request stream.*/
stream.Write(bytes, 0, pic.ContentLength);
}
/*Creating a WebResponse object by calling the GetResponse method of WebRequest object.*/
using (System.Net.HttpWebResponse webResponse = (System.Net.HttpWebResponse)webRequest.GetResponse())
{
/*Retrieving the response stream from the WebResponse object by calling the GetResponseStream method.*/
using (System.IO.StreamReader sr = new System.IO.StreamReader(webResponse.GetResponseStream()))
{
string path = sr.ReadToEnd();
}
}
then in another solution i was getting it to save the file.
public void SaveImage()
{
try
{
/*Retrieving the file name from the headers in the request. */
string destinationFileName = Path.Combine(#"~/" + "Portfolio" + "/", Request.Headers["FileName"].ToString());
string fileName = System.Web.HttpContext.Current.Server.MapPath(destinationFileName);
//string path = System.IO.Path.Combine(Server.MapPath("."), Request.Headers["FileName"].ToString());
using (System.IO.FileStream fileStream = System.IO.File.Create(fileName))
{
/*Getting stream from the Request object.*/
using (System.IO.Stream stream = Request.InputStream)
{
int byteStreamLength = (int)stream.Length;
byte[] byteStream = new byte[byteStreamLength];
/*Reading the stream to a byte array.*/
stream.Read(byteStream, 0, byteStreamLength);
/*Writing the byte array to the harddisk.*/
fileStream.Write(byteStream, 0, byteStreamLength);
}
}
Response.Clear();
/*Writing the status to the response.*/
Response.Write(fileName);
}
catch (Exception ex)
{
/*Writing the error message to the response stream.*/
Response.Clear();
Response.Write("Error: " + ex.Message);
}
}
So what should i change in code so that i could save the file on another location on another server without writing the code on two different place.
I've got a solution for this problem and its working fine.
public static void UploadFtpFile(string folderName, string fileName)
{
FtpWebRequest request;
try
{
//string folderName;
//string fileName;
string absoluteFileName = Path.GetFileName(fileName);
request = WebRequest.Create(new Uri(string.Format(#"ftp://{0}/{1}/{2}", "ftp.site4now.net", folderName, absoluteFileName))) as FtpWebRequest;
request.Method = WebRequestMethods.Ftp.UploadFile;
request.UseBinary = true;
request.UsePassive = true;
request.KeepAlive = true;
request.Credentials = new NetworkCredential("Username", "Password");
request.ConnectionGroupName = "group";
using (FileStream fs = System.IO.File.OpenRead(fileName))
{
byte[] buffer = new byte[fs.Length];
fs.Read(buffer, 0, buffer.Length);
fs.Close();
Stream requestStream = request.GetRequestStream();
requestStream.Write(buffer, 0, buffer.Length);
requestStream.Flush();
requestStream.Close();
}
}
catch (Exception ex)
{
}
}
Follow Below Sample
This sample is for creating a folder on another server over FTP protocol. Please extend it as per need.
using System;
using System.Net;
class Test
{
static void Main()
{
WebRequest request = WebRequest.Create("ftp://host.com/directory");
request.Method = WebRequestMethods.Ftp.MakeDirectory;
request.Credentials = new NetworkCredential("user", "pass");
using (var resp = (FtpWebResponse) request.GetResponse())
{
Console.WriteLine(resp.StatusCode);
}
}
}
As per the comment by #ADyson you must enable the FTP Protocol before working using this sample
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 have got the following code, I need to upload multiple files which don't have an extension/type assigned to them. The following code below works, but not on these files as it's trying to make a file for example called: ftp.server/file
Here is my code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Net;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
String sourcefilepath = #"path"; // e.g. “d:/test.docx”
String ftpurl = #"ftp"; // e.g. ftp://serverip/foldername/foldername
String ftpusername = #"user"; // e.g. username
String ftppassword = #"pass"; // e.g. password
string[] filePaths = Directory.GetFiles(sourcefilepath);
// Get the object used to communicate with the server.
foreach (string filename in filePaths)
{
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftpurl + Path.GetFileName(filename));
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(sourcefilepath);
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();
}
}
}
}
The files are from an iPhone backup, iPhone backups don't give the files extensions so I need a work around.
The solution I found was to copy the files and add a dummy extension.
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.
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();
}