Search code examples
asp.netrazorrootwebmatrixmappath

Save file in a folder above the site files


My host has the following structure:

/Web -> Where is the content of the site /Data -> Folder permissions to read and write

How do I upload a file to the Data folder? The code below does not work, since "~" returns the directory / web.

//Save Image
var serverPath = Server.MapPath(Href("~/Data/") + id);
Directory.CreateDirectory(serverPath);
imgOri.Save(Path.Combine(serverPath, fileName));

Solution

  • Server.MapPath() is designed to map a path up to the root directory of the application. As you are trying to upload a file above the root it won't work.

    You can upload a file above the root by specifying the exact file path (if the host can provide it):

    var serverPath = "C:\YourFolder\Data\") + id);

    I'm surprised your host is allowing you to upload a file outside of the root directory as there are a number of dangers in doing this...you may also run into Trust issues.