Server.MapPath - Could not find a part of the path

2019-08-31 14:23发布

问题:

I am uploading a file to my server using Server.MapPath

When I run my code I get the following error

Could not find a part of the path 'C:\inetpub\wwwroot\wss\VirtualDirectories\80\SitePages\uploads\ABI Employee List.xlsx'.

So Yes, I dont have that directory on my server. I only have a directory up to here.

'C:\inetpub\wwwroot\wss\VirtualDirectories\80\

So, I go and create Those directories.

The weird thing is, is that if I create a folder with the name "SitePages" in the above directory, my site doesn't even want to start up? Delete it and it works again. (Image of error below)

I need to create that directory to upload the file to my server, but I can't, since everything breaks. How will i fix this?

回答1:

create a directory in root eg. 'Foldername' and try the following

  DirectoryInfo dir = new DirectoryInfo(HttpContext.Server.MapPath("~/Foldername/"));
            if (!dir.Exists)
            {
                dir.Create();
            }
            // this makes sure that directory has been created
            // do other stuff


回答2:

You have create one folder name manually in virtual directory and try this code:

    public static string GetPath()
    {
        string Path = string.Empty;
        try
        {
            Path = HttpContext.Current.Server.MapPath("~/FolderName/");
        }
        catch (Exception _e)
        {
        }
        return Path;
    }


回答3:

try to create the desired folder at runtime. you can create a directory by

if(!Directory.Exists("YourDirectory"))
{
Directory.CreateDirectory("YourDirectory")
}


回答4:

create a directory in root eg. 'Images' and try the following

protected void Page_Load(object sender, EventArgs e)
{
}

protected void Button1_Click(object sender, EventArgs e)
{
    FileUpload1.SaveAs(Server.MapPath("~\\Images\\" + FileUpload1.FileName));
}