2011-04-10 67 views
1

我試圖從本地磁盤加載圖像,它的工作。但我的問題是,我想檢查圖像是否在文件夾中,如果沒有 - 然後MessageBox.Show(「沒有圖像!」);從C#本地磁盤加載和檢查圖像#

導入圖像:

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

你不應該結合'@'和''\\。 – SLaks 2011-04-10 14:21:50

+0

你也應該驗證如果一個文件是名字Picutre.png但它不是一個Picutre,搜索特定的例外! – Burimi 2011-04-10 14:34:37

+0

當您使用'@'符號時,您可以像使用瀏覽器時那樣使用路徑。你不再需要逃避斜線。 – 2011-04-10 14:36:47

回答

6

你可以使用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); 
} 
+0

在'ASP.NET'最好是'Server.MapPath(「文檔/圖片」),否則它會查找Windows系統文件夾中的文件.. :) – 2011-04-10 14:20:41

+0

@Shadow Wizard,絕對是事實上在ASP.NET中它應該是:'Server.MapPath(「〜/ Documentation/Pictures」)' – 2011-04-10 14:21:16

+0

@Darin如果OP想從它相對於當前'.aspx'的位置獲得它的話。 – 2011-04-10 14:26:14

0

嘗試使用用於測試的File.Exists方法,如果文件本身存在。 但是請注意,在調用該方法和調用實際加載文件的方法之間,該文件可能已經不存在了。因此,應該使用異常處理。

有關更多信息,請參閱this link

0

試試這個

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