Search code examples
c#asp.netasp.net-mvc-5asyncfileupload

Change Upload File path in c# asp.net Core


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.


Solution

  • You can't acces any file outside your web app root file unless you use one of theses otpions :

    1. Use an upload file controler :

      <input  type="file" name="UploadFile" /></span>
      

    In wich you have to let the user specify the file HE wants to upload.

    1. You can use FTP, you'll have to make a server yourself.

    I'm not an ASP expert, but i know this one thing :

    Being able to freely go through the files in the C:\ using code behind of a web application would represent a MAJOR LACK of security.

    EDIT :

    And this is THE way to give a file to your users :

        private void UserDownload(string fileOutPutName, string fileType, string fileContentPath)
        {
    
            Response.Clear();
            Response.AddHeader("content-disposition", "attachment;filename=" + Server.UrlPathEncode(fileOutPutName));
            Response.ContentType = fileType;
            try
            {
                Response.WriteFile(fileContentPath);
            }
            catch
            {}
            Response.End();
        }
    

    The file is gonna end up in their browser's download folder. Being able to write a file into a client's C:\ would be as unsafe as accessing his C:\

    ASP.NET won't let you do that