convert from physical path to virtual path

I have this function that gets the fileData as a byte array and a file path. The error I am getting is when it tries to set the fileInfo in the code bewlo. It says ‘Physical Path given, Virtual Path expected’

 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;
        }
    }

When debugging it, is providing the filePath as "E:\WEBS\webapp\default\images\mains\myimage.jpg" . And the error message is
'E:/WEBS/webapp/default/images/mains/myimage.jpg' is a physical path, but a virtual path was expected.

Also, what it is triggering this to happen is the following call
properties.ResizeImage(imageName, Configurations.ConfigSettings.MaxImageSize, Server.MapPath(Configurations.EnvironmentConfig.LargeImagePath));

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

If you already have a physical path, it doesn’t make sense to call Server.MapPath.

You’re calling MapPath twice.

Method 2

Working:

    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
    }

Not Working:
    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 
    }

Dont use Server.Mappath twice

Method 3

I take it that your project is located at:

E:WEBS\webapp

You should try and use relative references to your images e.g.
..defaultimagesmainsmyimage.jpg


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x