Server.MapPath returning a path with a folder that doesn’t exists

社会主义新天地 提交于 2020-01-15 19:12:30

问题


I have following code:

var dir = @"Content\Posts\" + yr + @"\" + mnth + @"\";
var a = Path.Combine(dir, dy.ToString() + pId.ToString() + ".txt");
//a contains: "Content\\Posts\\2013\\8\\file01.txt"
stts = obj.NotifyMail(title, writeup, "author@gmail.com", a);

And than in NotifyMail function I have this:

public bool NotifyMail(string subject, string body, string toAdd, string filePath)
    {
        …
string attachments = HttpContext.Current.Server.MapPath(filePath);
//NOW here attachments contains: "G:\\Program Files\\Derby\\Work\\Development\\proj\\proj\\`Post`\\Content\\Posts\\2013\\8\\file01.txt"

            var attchmnts = new LinkedResource(attachments);
            attchmnts.ContentId = "attchmnts";
…
    }

Now the problem is in NotifyMail when attachments is retrieving physical file path through Server.MapPath its returning a path with an invalid folder included in it i.e. Post this folder doesn't exists anywhere, not even in the hard drive and I have no idea how it is been picked up and returned. But said this due to this problem LinkedResource(attachments); is throwing an exception:

{"Could not find a part of the path ‘G:\\Program Files\\Derby\\Work\\Development\\proj\\proj\\Post\\Content\\Posts\\2013\\8\\file01.txt"’

回答1:


I don't believe MapPath guarantees that a path exists, it just tacks your virtual path to the context path.

I think your problem is that you're using

 HttpContext.Current.Server.MapPath

try using

HttpContext.Current.Request.MapPath



回答2:


I had a similar issue, You just need to add an extra "\\" double backslash before your filepath, like below and the extra "Post" word (which is your class name) will be gone.

public bool NotifyMail(string subject, string body, string toAdd, string filePath)
    {
string attachments = HttpContext.Current.Server.MapPath(@"\\" + filePath);

            var attchmnts = new LinkedResource(attachments);
            attchmnts.ContentId = "attchmnts";
    }


来源:https://stackoverflow.com/questions/18105250/server-mappath-returning-a-path-with-a-folder-that-doesn-t-exists

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!