2014-03-26 155 views
1

我的圖像不在資源中,但位於磁盤上。該文件夾與應用程序有關。我用:WPF從文件夾加載圖像

Overview_Picture.Source = new BitmapImage(new Uri(String.Format("file:///{0}/../MyImages /myim.jpg", Directory.GetCurrentDirectory()))); 
Overview_Picture.Source = new BitmapImage(uriSource); 

但是,這些類型的代碼產生了許多問題和搞砸了GetCurrentDirectory回報的某個時候確定,有時沒有。

因此,MyImages文件夾位於調試文件夾旁邊,我怎樣才能在那裏使用它們的圖像,而不是像我這樣做,在一些其他更正確的方式?

回答

2

正如在SO上經常提到的那樣,GetCurrentDirectory方法根據定義並不總是返回您的程序集所在的目錄,而是當前的工作目錄。兩者之間有很大的區別。

你需要的是當前的裝配文件夾(及其父代)。另外,我不確定是否需要圖片是安裝文件夾上方的一個文件夾(基本上,當您說它們位於Debug文件夾之上一層時基本上是這樣說的 - 在現實生活中這將是一個文件夾在應用程序安裝到的文件夾上方)。

使用以下命令:

string currentAssemblyPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); 
string currentAssemblyParentPath = Path.GetDirectoryName(currentAssemblyPath); 

Overview_Picture.Source = new BitmapImage(new Uri(String.Format("file:///{0}/MyImages/myim.jpg", currentAssemblyParentPath))); 

此外,還有MyImages後流浪空間,我刪除。

0

從相對文件路徑構造絕對Uri的替代方法是從相對路徑打開FileStream,並將其分配給BitmapImage的StreamSource屬性。但是請注意,當您想要在初始化BitmapImage後立即關閉流時,您還必須設置BitmapCacheOption.OnLoad

var bitmap = new BitmapImage(); 

using (var stream = new FileStream("../MyImages/myim.jpg", FileMode.Open)) 
{ 
    bitmap.BeginInit(); 
    bitmap.CacheOption = BitmapCacheOption.OnLoad; 
    bitmap.StreamSource = stream; 
    bitmap.EndInit(); 
    bitmap.Freeze(); // optional 
} 

Overview_Picture.Source = bitmap;