So from what I understand, you’re getting an “error” because you specifically tell the code to write an error even on success. Try to make your code easier to read. I set up a simple page to test the problem you’re having. In the HTML I have:
<body>
<form id="form1" runat="server">
<div>
<asp:Image runat="server" ID="TestPicture" />
</div>
</form>
</body>
Then the following code is in the CodeBehind. First it checks to make sure if the file exists it sets the URL of the image to the path. If the file doesn’t exist, it simply sets the URL of the image to “”.
protected void Page_Load(object sender, EventArgs e)
{
string serverPath = Server.MapPath("~/Test/") + Path.GetFileName("~/Test/TestImg.jpg");
string imgUrl = "~/Test/TestImg.jpg";
if (File.Exists(serverPath))
{
TestPicture.ImageUrl = imgUrl;
}
else
{
TestPicture.ImageUrl = "";
//TestPicture.Visible = false;
//TestPicture.ImageUrl = "Picture Not Available.jpg";
//or do other error checking here
}
}
For me, when the file exists, the image displays on the web page. When the file is non-existent, there is no image available. I commented out some other options that might make sense for you as well. The “Picture Not Available.jpg” might be a stock image that you could use to show that an image is not available.
If you’re still having problems, make sure to put breakpoints in your code and look at what’s actually happening.
solved File exist on server using C#, asp.net