Change Upload File path in c# asp.net Core

Rani Balaa picture Rani Balaa · Jun 17, 2016 · Viewed 8.1k times · Source

I want to change the path from the current root folder to mt C: or desktop for example, i'm using this code:

public IActionResult About(IList<IFormFile> files)
{

    foreach (var file in files)
    {
        var filename = ContentDispositionHeaderValue
                        .Parse(file.ContentDisposition)
                        .FileName
                        .Trim('"');
        filename = hostingEnv.WebRootPath + $@"\{filename}";

        using (FileStream fs = System.IO.File.Create(filename))
        {
            file.CopyTo(fs);
            fs.Flush();
        }
    }


    return View();
}

I tried changing the webrootpath or manipulating after the$@ but to no avail.

Answer

Jeffery Thompson picture Jeffery Thompson · Mar 13, 2017

The other answer seems to have confused downloading files from a server with uploading files.

IHostingEnvironment.WebRootPath is simply the path to the static files on your server (by default: the wwwroot folder). To save an uploaded file to a directory other than WebRootPath, you can simply replace the hostingEnv.WebRootPath with a full path to any other directory on the machine.

public IActionResult About(IList<IFormFile> files)
{
    foreach (var file in files)
    {
        var filename = ContentDispositionHeaderValue
                        .Parse(file.ContentDisposition)
                        .FileName
                        .Trim('"');
        filename = @"C:\UploadsFolder" + $@"\{filename}";

        using (FileStream fs = System.IO.File.Create(filename))
        {
            file.CopyTo(fs);
            fs.Flush();
        }
    }
    return View();
}

However, you must make sure that this directory exists, and that your application has permission to write to that directory. Running the app in debug from Visual Studio will run it as your user, so it will need to be a directory that you have access to write to. In a production environment, that gets more complicated and depends on your hosting setup.