将物理路径转换为虚拟路径

19

我有一个函数,它接收文件数据的字节数组和文件路径。我遇到的错误是在下面的代码中尝试设置fileInfo时出现的。它说:“给定物理路径,期望虚拟路径”。

 public override void WriteBinaryStorage(byte[] fileData, string filePath)
    {
        try
        {
            // Create directory if not exists.
            System.IO.FileInfo fileInfo = new System.IO.FileInfo(System.Web.HttpContext.Current.Server.MapPath(filePath)); //when it gets to this line the error is caught
            if (!fileInfo.Directory.Exists)
            {
                fileInfo.Directory.Create();
            }

            // Write the binary content.
            System.IO.File.WriteAllBytes(System.Web.HttpContext.Current.Server.MapPath(filePath), fileData);
        }
        catch (Exception)
        {
            throw;
        }
    }

在调试时,将文件路径提供为"E:\\WEBS\\webapp\\default\\images\\mains\\myimage.jpg"。而错误信息是

'E:/WEBS/webapp/default/images/mains/myimage.jpg' is a physical path, but a virtual path was expected.

同时,引起这种情况发生的是以下调用:

properties.ResizeImage(imageName, Configurations.ConfigSettings.MaxImageSize, Server.MapPath(Configurations.EnvironmentConfig.LargeImagePath));

请问为什么会有负评,我是C#的新手。请多多包涵。 - user710502
你理解MapPath的作用以及你的代码尝试做什么了吗? - SLaks
这是现有的代码,我没有编写它。我的理解是 MapPath 是一个函数,它将获取虚拟路径并将其转换为服务器路径?但是,我是新手,可能会忽略一些显而易见的东西。毫不失礼地说,我来到这个论坛是为了问一个我不确定的问题。没必要投反对票...我想这就是论坛存在的意义,不是吗?否则,我只会逐个查看个人资料并进行一堆负面评价,仅仅是因为好玩。 - user710502
没错。一旦你调用它一次,再对该结果进行调用就没有意义了。代码和错误信息已经足够清晰,我认为你应该能够意识到这一点。 - SLaks
好的,谢谢你,现在更清楚了。感谢你的耐心。 - user710502
3个回答

37
如果您已经有物理路径,调用 Server.MapPath 就没有意义了。
您调用了两次 MapPath

1
谢谢,那么我不使用Server.MapPath,该用什么替换这行代码呢? - user710502
1
有时候发现愚蠢的错误就是那么微不足道。 - Max Favilli

5

工作:

    string[] filesPath = Directory.GetFiles(Server.MapPath("~/txtPath/"));        
    foreach (string path in filesPath)
    {
        FileInfo fi = new FileInfo(path);      //This Is Working
       string LastAcceTime = fi.LastWriteTime; //Return Correct Value
    }

无法正常工作:

    string[] filesPath = Directory.GetFiles(Server.MapPath("~/txtPath/"));        
    foreach (string path in filesPath)
    {
        FileInfo fi = new FileInfo(Server.MapPath(path));  //This Is Worng
       string LastAcceTime = fi.LastWriteTime;             //Return 1/1/1601 
    }

不要两次使用 Server.MapPath

2
我理解您的项目位于以下地址:

E:\WEBS\\webapp\

你应该尝试使用相对引用来加载图片,例如:

..\default\images\mains\myimage.jpg

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接