2010-01-15 90 views
171

我有這段代碼,我該如何讓它接受所有典型的圖像格式? PNG,JPEG,JPG,GIF?將篩選器設置爲OpenFileDialog以允許使用典型的圖像格式?

這是我到目前爲止有:

public void EncryptFile() 
{    
    OpenFileDialog dialog = new OpenFileDialog(); 
    dialog.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*"; 
    dialog.InitialDirectory = @"C:\"; 
    dialog.Title = "Please select an image file to encrypt."; 

    if (dialog.ShowDialog() == DialogResult.OK) 
    { 
     //Encrypt the selected file. I'll do this later. :) 
    }    
} 

注意這個過濾器設置爲.txt文件。我可能更改爲PNG,但其他類型?

回答

211

the docs,你需要的過濾器語法如下:

Office Files|*.doc;*.xls;*.ppt 

即多個擴展用分號分隔 - 因此,Image Files|*.jpg;*.jpeg;*.png;...

+0

直接點。 – mjb 2017-10-09 03:16:26

9

對於圖像,您可以從GDI(System.Drawing)獲得可用的編解碼器,並通過一些工作構建您的列表。這將是最靈活的方式。

ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders(); 
+3

感謝您的提示!我添加了這些,它像一個魅力: 'var imageExtensions = string.Join(「;」,ImageCodecInfo.GetImageDecoders()。Select(ici => ici.FilenameExtension));' 'dialog.Filter = string .Format(「Images | {0} |所有文件| *。*」,imageExtensions);' – atlantis 2014-02-25 02:21:33

+0

呃......不知道如何在評論中做多行代碼塊: – atlantis 2014-02-25 02:24:02

+0

@atlantis可能更好地編輯帖子本身的代碼... – vapcguy 2016-10-04 17:02:05

53

這裏的ImageCodecInfo建議(以VB)的例子:

 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", "*.*") 

它看起來是這樣的:

enter image description here

+1

Imports System.Drawing.Imaging ;-) – FastAl 2017-02-01 14:23:58

37

在C#完整的解決方案是在這裏:

private void btnSelectImage_Click(object sender, RoutedEventArgs e) 
{ 
    // Configure open file dialog box 
    Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog(); 
    dlg.Filter = ""; 

    ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders(); 
    string sep = string.Empty; 

    foreach (var c in codecs) 
    { 
     string codecName = c.CodecName.Substring(8).Replace("Codec", "Files").Trim(); 
     dlg.Filter = String.Format("{0}{1}{2} ({3})|{3}", dlg.Filter, sep, codecName, c.FilenameExtension); 
     sep = "|"; 
    } 

    dlg.Filter = String.Format("{0}{1}{2} ({3})|{3}", dlg.Filter, sep, "All Files", "*.*"); 

    dlg.DefaultExt = ".png"; // Default file extension 

    // Show open file dialog box 
    Nullable<bool> result = dlg.ShowDialog(); 

    // Process open file dialog box results 
    if (result == true) 
    { 
     // Open document 
     string fileName = dlg.FileName; 
     // Do something with fileName 
    } 
} 
128

遵循這個模式,如果你瀏覽的圖像文件:

dialog.Filter = "Image files (*.jpg, *.jpeg, *.jpe, *.jfif, *.png) | *.jpg; *.jpeg; *.jpe; *.jfif; *.png"; 
+3

可能想擺脫管道字符之前和之後的空格過濾器部分中的分號和星號。但好,否則。 – vapcguy 2016-10-04 14:46:06

15

要過濾的圖像文件,請使用此代碼示例。

//Create a new instance of openFileDialog 
OpenFileDialog res = new OpenFileDialog(); 

//Filter 
res.Filter = "Image Files|*.jpg;*.jpeg;*.png;*.gif;*.tif;..."; 

//When the user select the file 
if (res.ShowDialog() == DialogResult.OK) 
{ 
    //Get the file's path 
    var filePath = res.FileName; 
    //Do something 
    .... 
} 
5

只是使用string.Join和LINQ的necrocomment。

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())); 
2

對於那些不想在這裏記住語法每次誰是一個簡單的封裝:

public class FileDialogFilter : List<string> 
{ 
    public string Explanation { get; } 

    public FileDialogFilter(string explanation, params string[] extensions) 
    { 
     Explanation = explanation; 
     AddRange(extensions); 
    } 

    public string GetFileDialogRepresentation() 
    { 
     if (!this.Any()) 
     { 
      throw new ArgumentException("No file extension is defined."); 
     } 

     StringBuilder builder = new StringBuilder(); 

     builder.Append(Explanation); 

     builder.Append(" ("); 
     builder.Append(String.Join(", ", this)); 
     builder.Append(")"); 

     builder.Append("|"); 
     builder.Append(String.Join(";", this)); 

     return builder.ToString(); 
    } 
} 

public class FileDialogFilterCollection : List<FileDialogFilter> 
{ 
    public string GetFileDialogRepresentation() 
    { 
     return String.Join("|", this.Select(filter => filter.GetFileDialogRepresentation())); 
    } 
} 

用法:

FileDialogFilter filterImage = new FileDialogFilter("Image Files", "*.jpeg", "*.bmp"); 
FileDialogFilter filterOffice = new FileDialogFilter("Office Files", "*.doc", "*.xls", "*.ppt"); 

FileDialogFilterCollection filters = new FileDialogFilterCollection 
{ 
    filterImage, 
    filterOffice 
}; 

OpenFileDialog fileDialog = new OpenFileDialog 
{ 
    Filter = filters.GetFileDialogRepresentation() 
}; 

fileDialog.ShowDialog(); 
6

我喜歡湯姆·福斯特的回答是最好的。這是他的解決方案的C#版本,但簡化了一些事情。

var codecs = ImageCodecInfo.GetImageEncoders(); 
var codecFilter = "Image Files|"; 
foreach (var codec in codecs) 
{ 
    codecFilter += codec.FilenameExtension + ";"; 
} 
dialog.Filter = codecFilter; 
-1

這是極端,但是我建立一個名爲FILE_TYPES 2列的數據庫表中的動態,數據庫驅動的過濾器,用字段名的延伸和DOCTYPE:

--------------------------------- 
| EXTENSION | DOCTYPE   | 
--------------------------------- 
| .doc  | Document  | 
| .docx | Document  | 
| .pdf  | Document  | 
| ...  | ...    | 
| .bmp  | Image   | 
| .jpg  | Image   | 
| ...  | ...    | 
--------------------------------- 

很顯然,我有很多不同類型的和擴展,但我正在簡化它的例子。這裏是我的功能:

private static string GetUploadFilter() 
    { 
     // Desired format: 
     // "Document files (*.doc, *.docx, *.pdf)|*.doc;*.docx;*.pdf|" 
     // "Image files (*.bmp, *.jpg)|*.bmp;*.jpg|" 

     string filter = String.Empty; 
     string nameFilter = String.Empty; 
     string extFilter = String.Empty; 

     // Used to get extensions 
     DataTable dt = new DataTable(); 
     dt = DataLayer.Get_DataTable("SELECT * FROM FILE_TYPES ORDER BY EXTENSION"); 

     // Used to cycle through doctype groupings ("Images", "Documents", etc.) 
     DataTable dtDocTypes = new DataTable(); 
     dtDocTypes = DataLayer.Get_DataTable("SELECT DISTINCT DOCTYPE FROM FILE_TYPES ORDER BY DOCTYPE"); 

     // For each doctype grouping... 
     foreach (DataRow drDocType in dtDocTypes.Rows) 
     { 
      nameFilter = drDocType["DOCTYPE"].ToString() + " files ("; 

      // ... add its associated extensions 
      foreach (DataRow dr in dt.Rows) 
      { 
       if (dr["DOCTYPE"].ToString() == drDocType["DOCTYPE"].ToString()) 
       { 
        nameFilter += "*" + dr["EXTENSION"].ToString() + ", "; 
        extFilter += "*" + dr["EXTENSION"].ToString() + ";"; 
       }      
      } 

      // Remove endings put in place in case there was another to add, and end them with pipe characters: 
      nameFilter = nameFilter.TrimEnd(' ').TrimEnd(','); 
      nameFilter += ")|"; 
      extFilter = extFilter.TrimEnd(';'); 
      extFilter += "|"; 

      // Add the name and its extensions to our main filter 
      filter += nameFilter + extFilter; 

      extFilter = ""; // clear it for next round; nameFilter will be reset to the next DOCTYPE on next pass 
     } 

     filter = filter.TrimEnd('|'); 
     return filter; 
    } 

    private void UploadFile(string fileType, object sender) 
    {    
     Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog(); 
     string filter = GetUploadFilter(); 
     dlg.Filter = filter; 

     if (dlg.ShowDialog().Value == true) 
     { 
      string fileName = dlg.FileName; 

      System.IO.FileStream fs = System.IO.File.OpenRead(fileName); 
      byte[] array = new byte[fs.Length]; 

      // This will give you just the filename 
      fileName = fileName.Split('\\')[fileName.Split('\\').Length - 1]; 
      ... 

應該產生一個過濾器,看起來像這樣:

enter image description here

+0

Downvoter,小心解釋一下?你有更好的主意嗎?我的工作,正如我通過圖表演示的那樣。 – vapcguy 2017-07-19 15:46:51

+2

'Filter =「文檔文件(* .doc,*。docx,*。pdf)| * .doc; *。docx,*。pdf |圖像文件(* .bmp,*。jpg)| * .bmp; * .jpg「;'這應該產生一個過濾器,看起來像上面答案中的最後一張圖片。 – mjb 2017-10-09 03:21:55

+0

@mjb如果你看了我的答案,你會發現我已經在代碼頂部的評論中有過。如果它不起作用,我就不會有圖形來證明它的確如此。正如我所解釋的,代碼從數據庫表中獲取值並連接它們。您只需將Doctype(「文檔」,「圖像」等)和擴展名作爲2列放在名爲「FILE_TYPES」的表上。假設你有一個名爲'DataLayer.Get_DataTable()'的函數,它將採用我在這段代碼中的SQL命令併發回給你一個DataTable,它會爲你做所有事情。正如我所說,是的,是極端的,但它確實有效。 – vapcguy 2017-10-13 00:56:47

1

爲了匹配不同類別的文件的列表,你可以使用過濾器是這樣的:

 var dlg = new Microsoft.Win32.OpenFileDialog() 
     { 
      DefaultExt = ".xlsx", 
      Filter = "Excel Files (*.xls, *.xlsx)|*.xls;*.xlsx|CSV Files (*.csv)|*.csv" 
     }; 
相關問題