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

use*_*502 15 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;
        }
    }
Run Code Online (Sandbox Code Playgroud)

在调试时,提供filePath为"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.
Run Code Online (Sandbox Code Playgroud)

此外,触发此操作的是以下调用

properties.ResizeImage(imageName, Configurations.ConfigSettings.MaxImageSize, Server.MapPath(Configurations.EnvironmentConfig.LargeImagePath));
Run Code Online (Sandbox Code Playgroud)

SLa*_*aks 23

如果您已经有物理路径,则呼叫没有意义Server.MapPath.

你打了MapPath两次电话.


小智 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
    }
Run Code Online (Sandbox Code Playgroud)

不工作:

    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 
    }
Run Code Online (Sandbox Code Playgroud)

不要使用Server.Mappath两次