Dhananjaya
Dhananjaya

Reputation: 1615

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

Upvotes: 0

Views: 1591

Answers (2)

iJay
iJay

Reputation: 4293

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();
    }

Upvotes: 0

Giedrius
Giedrius

Reputation: 8540

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).

Upvotes: 1

Related Questions