我在Visual Studio项目文件夹中有一个图像文件,将其构建操作设置为“资源”,因此它包含在我的exe文件中。
我可以毫无问题地在xaml中链接到这个文件,例如<Image Source="images/myimage.png">
,它可以正常工作。
但是,如果我尝试检查该文件的存在性,使用File.exists("images/myimage.png")总是返回false。我做错了什么?
我在Visual Studio项目文件夹中有一个图像文件,将其构建操作设置为“资源”,因此它包含在我的exe文件中。
我可以毫无问题地在xaml中链接到这个文件,例如<Image Source="images/myimage.png">
,它可以正常工作。
但是,如果我尝试检查该文件的存在性,使用File.exists("images/myimage.png")总是返回false。我做错了什么?
如果您不想将它作为附加项捆绑到输出文件夹中,则无需采取任何措施。它已经构建到您的exe中,不需要检查。始终为真。
好的,我理解了,因为您动态构建嵌入式资源的名称,所以您想要检查它。
请看这里:WPF - check resource exists without structured exception handling
他们基本上针对 Assembly.GetExecutingAssembly().GetManifestResourceNames()
进行检查。
您可以将其用作起点。但请注意,资源名称不是 images/myimage.png ,而是从您的命名空间构建,例如 YourApp.images.myimage.png。您可能会想查看该答案中内置资源名称数组的内容。
Xamarin.Forms
从一段有效的代码中,检查自动生成的文件名是否存在于共享项目的嵌入式资源中(如此处所述https://developer.xamarin.com/guides/xamarin-forms/user-interface/images/#Embedded_Images)。var assembly = typeof(App).GetTypeInfo().Assembly;
var AssemblyName = assembly.GetName().Name;
var generatedFilename = AssemblyName+".Images.flags.flag_" + item.CountryCode?.ToLower() + @".png";
bool found = false;
foreach (var res in assembly.GetManifestResourceNames())
{
if (res == generatedFilename)
{
found = true;
break;
}
}
if (found)
UseGeneratedFilename();
else
UseSomeOtherPlaceholderImage;
private string GetExecutingAssemblyPath()
{
string codeBase = Assembly.GetExecutingAssembly().CodeBase;
UriBuilder uri = new UriBuilder(codeBase);
string path = Uri.UnescapeDataString(uri.Path);
return Path.GetDirectoryName(path);
}
干杯。