2009-09-07 41 views
27

我在C#WPF應用程序中將其構建操作設置爲'Resource'。它只是源目錄中的一個文件,它沒有通過拖放屬性對話框添加到應用程序的資源集合中。我試圖把它寫成流,但是儘管嘗試了很多點,斜槓,命名空間和看似其他所有的變體,我仍然無法打開它。程序集中的資源作爲流

我可以在xaml中使用「pack:// application:,,,/Resources/images/flags/tr.png」來訪問它,但我無法獲取包含它的流。

大部分地方好像說使用

using(BinaryReader reader = new BinaryReader(System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream("ResourceBlenderExpress.Resources.images.flags.tr.png"))) { 
    using(BinaryWriter writer = new BinaryWriter(File.OpenWrite(imageFile))) { 
     while((read = reader.Read(buffer, 0, buffer.Length)) > 0) { 
      writer.Write(buffer, 0, read); 
     } 
     writer.Close(); 
    } 
    reader.Close(); 
} 

我已經沒有任何運氣。

回答

23

GetManifestResourceStream是傳統的.NET資源即那些在RESX文件中引用。這些與WPF資源不同,即與Resource的構建操作一起添加的資源。要訪問這些文件,你應該使用Application.GetResourceStream,傳入相應的pack:URI。這將返回一個StreamResourceInfo對象,該對象具有Stream屬性來訪問資源的數據。

+0

謝謝,我從來沒有發現。 :) – Echilon 2009-09-07 09:49:30

1

沒有必要調用Close()方法,它將在using子句的末尾由Dispose()自動調用。所以,你的代碼可能是這樣的:

using(BinaryReader reader = new BinaryReader(System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream("ResourceBlenderExpress.Resources.images.flags.tr.png"))) 
using(BinaryWriter writer = new BinaryWriter(File.OpenWrite(imageFile))) 
{ 
    while((read = reader.Read(buffer, 0, buffer.Length)) > 0) 
    { 
     writer.Write(buffer, 0, read); 
    } 
} 
+0

這是如何回答這個問題的? – 2009-09-07 07:52:43

+0

真的嗎?有用的見解,如果它是真的。我一直認爲明確調用Close對於流/文件更好。 – Echilon 2009-09-07 12:13:52

+0

Using語句的使用明確調用Stream的dispose方法,它隱式調用它的Close方法。即使引發異常,using語句也總是處理「used」對象,所以using是一個包含全部的,幾乎沒有錯誤的語句。 – BeardinaSuit 2010-08-12 17:36:27

6

如果我得到你的權利,你需要打開資源流的問題,因爲你不知道它的確切名字嗎?如果是這樣,您可以使用

System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceNames() 

獲取所有包含資源的名稱列表。這樣你可以找到分配給你的圖像的資源名稱。

+0

爲什麼不使用'GetCallingAssembly'而不是'GetExecutingAssembly'? – Odys 2013-03-19 09:09:46

25

你可能尋找Application.GetResourceStream

StreamResourceInfo sri = Application.GetResourceStream(new Uri("Images/foo.png")); 
if (sri != null) 
{ 
    using (Stream s = sri.Stream) 
    { 
     // Do something with the stream... 
    } 
} 
+4

要添加,必須將文件構建爲「資源」。 http://stackoverflow.com/a/7394894/355264 – 2013-05-13 15:21:27