1

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; 
3
  • 4
    You shouldn't combine @ with \\ . Commented Apr 10, 2011 at 14:21
  • And you should also Validate if a File is name Picutre.png but it's not a Picutre ,search for specific Exception ! Commented Apr 10, 2011 at 14:34
  • When you use the @ symbol, you can use a path just as it appears on the explorer. You no longer have to escape the slashes. Commented Apr 10, 2011 at 14:36

3 Answers 3

5

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); } 
Sign up to request clarification or add additional context in comments.

6 Comments

In ASP.NET it better be Server.MapPath("Documentation/Pictures") otherwise it will look for the files in the system folder of Windows.. :)
@Shadow Wizard, yeah, absolutely, in fact in ASP.NET it should be: Server.MapPath("~/Documentation/Pictures")
@Shadow Wizard, what ASPX are you talking about? Can't see any reference in the OP about ASP.NET. Not to mention that pictureBox and ASP.NET, hmm...
@Darin: Can you elaborate on why you're using Path.ChangeExtension? Is there a specific reason?
@Sergio, it's safer, I always use file specific functions when dealing with files such as Path.Combine, Path.ChangeExtension, ... instead of string concatenations. For example if table[8] ends with a dot (.) the function will correctly handle the case whereas if you are using string concatenations you could end up with foo..jpg.
|
0

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.

Comments

0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.