Setting the filter to an OpenFileDialog to allow the typical image formats?

前端 未结 11 1010
陌清茗
陌清茗 2020-12-22 16:07

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


        
11条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-22 16:26

    For those who don't want to remember the syntax everytime here is a simple encapsulation:

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

    Usage:

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

提交回复
热议问题