简体   繁体   中英

Retrieve image “URI formats no supported” & “FileNotFoundException”

I'm just trying to retrieve an image in my project. But I am unable to make it work on the online server.

This code works fine on local server :

Image image = Image.FromFile("C:\\Users\\Nico\\Desktop\\Project\\MvcApplication1\\MvcApplication1\\Images\\sf.gif");

But I can't deploy it on my server.

The following code gives the exception "FileNotFoundException" .

Image image = Image.FromFile("\\Images\\sf.gif");

And this code gives "URI formats not supported"

Image image = Image.FromFile("http://www.mydomain.com/Images/sf.gif");

Any help is appreciated.

Where on the server is the file?

The first one works because you're referencing an existing file. The second one doesn't work likely because it can't find that file relative to whatever the current path is. You'll probably want to be more explicit with the path. The third one definitely won't work because that's not a file, it's a URL. (HTTP isn't a file system.)

Is the "Images" folder in the root of the application? Try prepending the second version with a "~" to indicate that:

Image image = Image.FromFile("~/Images/sf.gif");

If the "Images" folder can change from something more than just the root of the application, you can also use a config setting to indicate the location of the images. Something as simple as this:

<add key="imagesRoot" value="C:\Users\Nico\Desktop\Project\MvcApplication1\MvcApplication1\Images\" />

And then you can use the Path object to build a more complete path:

Image image = Image.FromFile(Path.Combine(ConfigurationManager.AppSettings["imagesRoot"], "sf.gif"));

For just the images folder of a website that might be overkill, but it's certainly flexible. And then you can point it to any folder via the config file whenever you need to change it or deploy it to a different server.

You can use Server.MapPath to let the code to detect the root folder of a website/application.

Image image = Image.FromFile(Path.Combine(Server.MapPath("/Images"), "sf.gif"));

It would be worth to check

Server.MapPath("."), Server.MapPath("~"), Server.MapPath(@"\\"), Server.MapPath("/"). What is the difference?

Try

Image image = Image.FromFile(Server.MapPath("\\Images\\sf.gif"));

<!-- language: c# -->
Image image = Image.FromFile ("Images\\sf.gif");
//OR
Image image = Image.FromFile (@"Images\sf.gif");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM