C# 使用图像而不将其添加到WPF项目/解决方案资源中
我正在为WPF应用程序中的楼层构建一个图库,我正在从csv文件中读取图像名称,用户将直接将图像复制到资源文件夹中C# 使用图像而不将其添加到WPF项目/解决方案资源中,c#,.net,wpf,C#,.net,Wpf,我正在为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 (!stre
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);
我无法将其添加到项目的资源文件夹中,也无法嵌入资源,因为我希望用户在资源文件夹中复制其文件,并在部署后更新csv文件
我的代码将读取它并显示gallery,但在这种情况下,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
函数的最后一行更改为:
return new BitmapImage(new Uri(assembly.GetName().CodeBase + pathInApplication, UriKind.Absolute));
这应该可以解决问题。
您还可以尝试使用UriKind.Relative
你好您在URI方案中使用了不正确的权限。应用程序权限用于编译时已知的数据文件(也称为静态资源)。您必须将其替换为原始授权的站点
我还建议用标准的CSV文件替换您的自滚文本文件格式。默认情况下,许多程序(如Excel)支持生成逗号分隔的字段。虽然可以放置自定义分隔符,但它们通常需要额外的工作。读取和解析逗号分隔的文件也更容易,因为有许多库可以执行这些任务。LoadBitmapFromResource的代码可能会很重要。如果您无论如何都不能将图像作为资源嵌入-您可以直接从文件系统加载它…有一个名为TextfieldParser,负责解析任何结构化文件。您需要在添加引用.NET选项卡中添加对Microsoft.VisualBasic的引用。尝试以下操作:在解决方案中,将映像“Build Action”属性设置为“Resource”,然后清理解决方案并重建它。
return new BitmapImage(new Uri(assembly.GetName().CodeBase + pathInApplication, UriKind.Absolute));