Wilky
Wilky

Reputation: 209

HttpPostedFile.SaveAs access denied

I'm trying to save a file that I upload from my page but I'm getting an access denied error:

public void SaveFile(Item item, HttpPostedFileBase file)
    {
        var dir = string.Format(@"{0}\NSN\{1}", ConfigurationManager.AppSettings["ContentLocation"].ToString(), item.Id.ToString());

        if (!System.IO.Directory.Exists(dir))
            System.IO.Directory.CreateDirectory(dir);

        Array.ForEach(Directory.GetFiles(dir), File.Delete);

        file.SaveAs(dir);
    }

I'm running this site from the local host from visual studio so no app pool is involved. I've given the Network Service (and Everyone as a test) full control of the folder and it's subfolders. Strange thing is it creates the folder if it needs to and also deletes any files in an existing folder. Only when I call the SaveAs function do I get the error.

Upvotes: 1

Views: 3592

Answers (2)

James
James

Reputation: 216

Here, give this a try:

string saveAsPath = Path.Combine(dir, file);
file.SaveAs(saveAsPath);

Replace file.SaveAs(dir) with the above.

Upvotes: 2

Rudis
Rudis

Reputation: 1217

You call file.SaveAs with path to directory instead of path to file

Upvotes: 6

Related Questions