I have this code, how can I allow it to accept all typical image formats? PNG, JPEG, JPG, GIF?
Here\'s what I have so far:
public void EncryptFile()
Here's an example of the ImageCodecInfo suggestion (in VB):
Imports System.Drawing.Imaging
...
Dim ofd as new OpenFileDialog()
ofd.Filter = ""
Dim codecs As ImageCodecInfo() = ImageCodecInfo.GetImageEncoders()
Dim sep As String = String.Empty
For Each c As ImageCodecInfo In codecs
Dim codecName As String = c.CodecName.Substring(8).Replace("Codec", "Files").Trim()
ofd.Filter = String.Format("{0}{1}{2} ({3})|{3}", ofd.Filter, sep, codecName, c.FilenameExtension)
sep = "|"
Next
ofd.Filter = String.Format("{0}{1}{2} ({3})|{3}", ofd.Filter, sep, "All Files", "*.*")
And it looks like this:
I like Tom Faust's answer the best. Here's a C# version of his solution, but simplifying things a bit.
var codecs = ImageCodecInfo.GetImageEncoders();
var codecFilter = "Image Files|";
foreach (var codec in codecs)
{
codecFilter += codec.FilenameExtension + ";";
}
dialog.Filter = codecFilter;
Follow this pattern if you browsing for image files:
dialog.Filter = "Image files (*.jpg, *.jpeg, *.jpe, *.jfif, *.png) | *.jpg; *.jpeg; *.jpe; *.jfif; *.png";
In order to match a list of different categories of file, you can use the filter like this:
var dlg = new Microsoft.Win32.OpenFileDialog()
{
DefaultExt = ".xlsx",
Filter = "Excel Files (*.xls, *.xlsx)|*.xls;*.xlsx|CSV Files (*.csv)|*.csv"
};
Just a necrocomment for using string.Join and LINQ.
ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders();
dlgOpenMockImage.Filter = string.Format("{0}| All image files ({1})|{1}|All files|*",
string.Join("|", codecs.Select(codec =>
string.Format("{0} ({1})|{1}", codec.CodecName, codec.FilenameExtension)).ToArray()),
string.Join(";", codecs.Select(codec => codec.FilenameExtension).ToArray()));