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

时间:2011-11-17 17:06:41

标签: c# asp.net

我有这个函数将fileData作为字节数组和文件路径获取。我得到的错误是它试图在代码bewlo中设置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));

3 个答案:

答案 0 :(得分:23)

如果您已有物理路径,则拨打Server.MapPath无效。

您正在拨打MapPath两次。

答案 1 :(得分:2)

工作:

    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 :(得分:1)

我认为你的项目位于:

E:\WEBS\\webapp\

您应该尝试使用对图像的相对引用,例如

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