【发布时间】:2013-07-03 17:07:07
【问题描述】:
我正在 WPF 应用程序中为楼层构建一个画廊,我正在从 csv 文件中读取图像名称,用户将直接将图像复制到资源文件夹中。
StreamReader streamReader = new StreamReader(
(Application.Current as PlayOnSurface.App).ProjectAmenitiesCSVPath);
// browse the csv file line by line until the end of the file
while (!streamReader.EndOfStream)
{
// for each line, split it with the split caractere (that may no be ';')
var splitLine = streamReader.ReadLine().Split('~');
if (int.Parse(splitLine[0].Trim())
== (Application.Current as PlayOnSurface.App).SelectedFloorID)
{
for (int i = 2; i < splitLine.Length; i++)
{
ImageList.Add(splitLine[i].Trim());
}
}
// map the splitted line with an entity
}
streamReader.Close();
btnPrev.IsEnabled = false;
if (ImageList.Count <= 1)
btnNext.IsEnabled = false;
imgGallery.Source = Utilities.LoadBitmapFromResource(
"Resources/Amenities/" + ImageList[0],
null);
实用程序代码
public static BitmapImage LoadBitmapFromResource(string pathInApplication, Assembly assembly = null)
{
if (assembly == null)
{
assembly = Assembly.GetCallingAssembly();
}
if (pathInApplication[0] == '/')
{
pathInApplication = pathInApplication.Substring(1);
}
return new BitmapImage(new Uri(@"pack://application:,,,/" + assembly.GetName().Name + ";component/" + pathInApplication, UriKind.Absolute));
}
我无法将其添加到项目的 Resources 文件夹中,也无法嵌入资源,因为我希望用户将其文件复制到 Resources 文件夹并在部署后更新 csv 文件。
我的代码将读取它并显示图库,但在这种情况下,WPF 在上述代码的imgGallery.Source 行上加载图像时会引发“无法定位资源”异常。
我的 csv 文件格式:
1~FirstFloor~img1.png~img2.png~img3.png
2~SecondFloor~img1.png~img2.png~img3.png
3~ThirdFloor~img1.png~img2.png~img3.png
4~FourthFloor~img1.png~img2.png~img3.png
【问题讨论】:
-
LoadBitmapFromResource的代码可能很重要。 -
如果您无论如何都无法将图像作为资源嵌入 - 您可以直接从文件系统加载它...
-
有一个名为 TextfieldParser 的 .Net 库负责解析任何结构化文件。您需要在 Add References .NET 选项卡中添加对 Microsoft.VisualBasic 的引用。 msdn.microsoft.com/en-us/library/…
-
试试这个:在解决方案探索中将图像“构建操作”属性设置为“资源”,然后清理解决方案并重建它。