0

我正在尝试获取图像运行时并基于 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();
    }
4

1 回答 1

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()如果您在其中有一段硬编码的路径,您应该将它放在上面的字符串中。

于 2013-11-19T02:49:37.643 回答