[英]confused about resources and GetManifestResourceNames()
我一直在學習C#和visual C#IDE中的資源。 我現在很困惑。 我已經閱讀了StackOverflow上的一些頁面,比如這個如何獲取一個embebbed資源的路徑和Microsoft的文檔,但它讓我很困惑。
我的第一個問題:什么是資源:它是.resources文件還是其中的文件,如圖標。
第二:當我使用GetManifestResourceNames方法時:我是否獲得.resources文件名或其中的文件名。 當我在我的程序中使用它時,我只獲取.resources文件,但是閱讀像這樣循環遍歷所有資源的resx文件的主題,我得到的印象我應該得到的名稱.resources文件中的文件。
是我,還是這個術語真的有點令人困惑? 任何人都可以讓它更清晰一點嗎? 謝謝你的幫助。
資源是您通過將其標記為“EmbeddedResource”來編譯的任何文件,這只是將文件合並到程序集中。 GetManifestResourceNames()
只是一個枚舉器,它為我們提供了所有嵌入式編譯資源文件的名稱,例如MyAssembly.resources
。 需要通過加載此資源文件的ResourceSet
枚舉實際資源元素。
我不知道你是否還需要這個問題的答案,但根據我的經驗, GetManifestResourceNames()
返回程序集中嵌入的.resource
文件的名稱。
如果您想訪問各個資源,您可以這樣做:
Assembly assembly = Assembly.LoadFrom(assemblyName);
string[] names = assembly.GetManifestResourceNames();
ResourceSet set = new ResourceSet(assembly.GetManifestResourceStream(names[0]));
foreach (DictionaryEntry resource in set)
{
Console.WriteLine("\n[{0}] \t{1}", resource.Key, resource.Value);
}
由於Felice Pollano的回答,我得到了我的項目。 我在我的解決方案中添加了一個名為Images的文件夾,並在Windows資源管理器中打開該文件夾,然后將我的圖像文件復制到Images文件夾中。 然后進入visual studio並單擊Solution Explorer頂部的“show all files”,右鍵單擊Images文件夾中的圖像文件,然后單擊Include in project。 然后我左鍵單擊解決方案資源管理器中的圖像文件,然后在“屬性”窗口中,將構建操作設置為嵌入式資源,就像您提到的那樣。
這是我訪問此圖片的代碼
private Dictionary<int, Image> GetImages()
{
List<Stream> picsStrm = new List<Stream>();
Assembly asmb = Assembly.GetExecutingAssembly();
string[] picNames = asmb.GetManifestResourceNames();
foreach (string s in picNames)
{
if (s.EndsWith(".png"))
{
Stream strm = asmb.GetManifestResourceStream(s);
if (strm != null)
{
picsStrm.Add(strm);
}
}
}
Dictionary<int, Image> images = new Dictionary<int, Image>();
int i = 0;
foreach (Stream strm in picsStrm)
{
PngBitmapDecoder decoder = new PngBitmapDecoder(strm,
BitmapCreateOptions.PreservePixelFormat,
BitmapCacheOption.Default);
BitmapSource bitmap = decoder.Frames[0] as BitmapSource;
Image img = new Image();
img.Source = bitmap;
img.Stretch = Stretch.UniformToFill;
images.Add(i, img);
i++;
strm.Close();
}
return images;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.