我正在尝试获取图像运行时并基于ImageFilePathName搜索图像。但是有可能图像不存在但仍然使用空图像创建源路径。如果源中包含有效的文件或图像,请任何人都可以建议如何检查。谢谢
public object Convert(object value, Type targetType, object parameter, string culture)
{
StorageFolder installFolder = Windows.ApplicationModel.Package.Current.InstalledLocation;
string installFolderPath = installFolder.Path;
const string LOGO_KIND_SMALL = "Small";
ImageSource source;
string logoImageFilePathName;
try
{
int logoId = Int32.Parse((string)value);
logoImageFilePathName = string.Format("{0}\\{1}\\Logos\\Chan\\{2}\\{3:0000}.png", installFolderPath, "Assets", LOGO_KIND_SMALL, logoId);
try
{
source = new BitmapImage(new Uri(logoImageFilePathName));
return source;
}
catch(Exception ex)
{
Logger.LogError(ex.Message);
}
}
catch (Exception ex)
{
Logger.LogError(ex.Message);
}
logoImageFilePathName = string.Format("{0}\\{1}\\Logos\\Channels\\{2}\\{3}.png", installFolderPath, "Assets", LOGO_KIND_SMALL, "0000");
source = new BitmapImage(new Uri(logoImageFilePathName));
return source;
}
public object ConvertBack(object value, Type targetType, object parameter, string culture)
{
throw new NotSupportedException();
}
答案 0 :(得分:2)
要检查并查看路径是否有效,您可以使用File.Exists(path);
。
但只是为了知识,如果你想看看字符串是否是一个路径,或只是文本Uri.IsWellFormedUriString(parameter, UriKind.Absolute)
所以你会使用:
public object Convert(object value, Type targetType, object parameter, string culture)
{
string installFolderPath = System.Windows.ApplicationModel.Package.Current.InstalledLocation.Path;
const string LOGO_KIND_SMALL = "Small";
var logoImageFilePathName = string.Format("{0}\\Assets\\Logos\\Chan\\{1}\\{2:0000}.png"
, installFolderPath
, LOGO_KIND_SMALL
, Int32.Parse((string)value));
// Check for file
return (File.Exists(logoImageFilePathName))
? new BitmapImage(new Uri(logoImageFilePathName))
: null;
}
public object ConvertBack(object value, Type targetType, object parameter, string culture)
{
throw new NotSupportedException();
}
只需注意:当您使用string.Format()
之类的方法时,如果您有一个硬编码的路径,那么您应该将其放在字符串中,如上所述。