在 Windows Forms 應用程式中,DataGridView 的 DataGridViewImageColumn 常用於顯示圖片。若直接使用絕對路徑,部署時極易因路徑變更導致圖片遺失;採用相對專案路徑(相對於執行檔目錄)才是穩健做法。
string imgPath = System.AppDomain.CurrentDomain.BaseDirectory + "Images\\photo.jpg";
// 或使用 Path.Combine 確保跨平台相容
string imgPath = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Images", "photo.jpg");
AppDomain.CurrentDomain.BaseDirectory:取得目前執行檔(.exe)所在目錄,結尾含反斜線。bin\Debug\Images\。// 假設資料來源為 DataTable,含 ImagePath 欄位存相對路徑
DataGridViewImageColumn imgCol = new DataGridViewImageColumn();
imgCol.DataPropertyName = "ImagePath"; // 綁定欄位
imgCol.ImageLayout = DataGridViewImageCellLayout.Zoom;
dataGridView1.Columns.Add(imgCol);
// CellFormatting 事件中動態載入圖片
private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
if (e.ColumnIndex == imgCol.Index && e.Value != null)
{
string relPath = e.Value.ToString();
string fullPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, relPath);
if (File.Exists(fullPath))
e.Value = Image.FromFile(fullPath);
else
e.Value = Properties.Resources.Placeholder; // 找不到圖顯示預設圖
}
}
Images\\user1.jpg)。File.Exists 失敗時拋出例外。BaseDirectory 會指向 AppData\Local\Apps\2.0\...,相對路徑機制依然有效。