Elfoc
Elfoc

Reputation: 3689

Loading and checking image from local disk in C#

i'm trying to load image from local disk, and it's working. But my problem is that i'd like to check if image is available in folder, and if not - then MessageBox.Show("No image!");

Loading image:

 Bitmap bitmap1 = new Bitmap(@"Documentation\\Pictures\\"+table[8]+".jpg");
 pictureBox.Image=bitmap1;

Upvotes: 1

Views: 8289

Answers (3)

Anuraj
Anuraj

Reputation: 19598

Try this

string fileName = string.Format(@"Documentation\\Pictures\\{0}.jpg",table[8]);
if(!File.Exists(fileName))
{
MessageBox.Show("No Image");
}
else
{
Picture1.Image = Image.FromFile(fileName);
}

Upvotes: 0

M.A. Hanin
M.A. Hanin

Reputation: 8074

Try using the File.Exists method for testing if the file itself exists. Note, however, that between invoking that method and invoking the method which actually loads the file, the file could already be gone. Thus, exception handling should be used nonetheless.

See this link for further info.

Upvotes: 0

Darin Dimitrov
Darin Dimitrov

Reputation: 1038800

You could use the File.Exists method to check whether a given file exists:

var file = Path.ChangeExtension(table[8], ".jpg");
var fullPath = Path.Combine(@"Documentation\Pictures", file);
if (!File.Exists(fullPath))
{
    MessageBox.Show("No image!");
}
else
{
    pictureBox.Image = new Bitmap(fullPath);
}

Upvotes: 6

Related Questions