I am using a FileToImageConverter
to display a image based on the file extension.
Everything works for normal extensions .xlsx, .doc, .docx, because I have a image for that extension in the Media folder, but if the filename has a extension that is not in the media folder of the project, then no image is being displayed. I want to try and assign a generic image for all file extensions that do not have a extension in the folder.
So if the file was test.sql then assign something like file_extension_file.png as the generic icon. the normal icons are stored like file_extension_xlsx.png
Here is the original Converter
public class ConvertFileImageConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (value as string == string.Empty) return null;
string file_extension = System.IO.Path.GetExtension(value.ToString());
file_extension = file_extension.Replace(".", "");
var file = @"/Media/file_extension_" + file_extension + ".png";
ImageSource src = new BitmapImage(new Uri(file, UriKind.Relative));
return src;
}
}
This is hitting the try still
if (value as string == string.Empty)
return null;
string file_extension = System.IO.Path.GetExtension(value.ToString());
file_extension = file_extension.Replace(".", "");
var file = @"/Media/file_extension_" + file_extension + ".png";
var genericfile = @"/Media/file_extension_file.png";
try
{
return new BitmapImage(new Uri(file, UriKind.Relative));
}
catch (FileNotFoundException exception)
{
return new BitmapImage(new Uri(genericfile, UriKind.Relative));
}
Updated: Here are some of the images etc.
This is setting everything to the default image with the !File exists even if the extension is in the folder.
private static ImageSource DefaultImage = new BitmapImage(new Uri(@"/Media/file_extension_file.png", UriKind.Relative));
public object Convert(object value,
Type targetType, object parameter, CultureInfo culture)
{
var filename = (string)value;
if(string.IsNullOrWhiteSpace(filename))
{
return DefaultImage;
}
var extension = Path.GetExtension(filename).Replace(".", string.Empty);
var imageName = @"/Media/file_extension_" + extension + ".png";
if (!File.Exists(imageName))
{
return DefaultImage;
}
return new BitmapImage(new Uri(imageName, UriKind.Relative));
}
The filenames being passed in look like test.doc, test.docx, test.sql, test.xls etc.
locals are showing below: the highlighted red is what it is looking for in the Media folder, but there is not one, so I am trying to show the Default Image.