System.IO.Dirctory.GetFiles(string path, string searchPattern)方法不支持选择多种格式的文件。
下面提供一个通过OpenFileDialog中支持的文件过滤器Filter获取多种格式文件的方法。
/// <summary> /// 根据文件过滤器获取指定目录下的文件 /// </summary> /// <param name="directoryPath"></param> /// <param name="filter">Example:"doc file|*.doc|txt file|*.txt"</param> /// <returns></returns> public List<string> GetDirectoryFiles(string directoryPath, string filter) { if (Directory.Exists(directoryPath) == false) { throw new DirectoryNotFoundException(String.Format("/'{0}/' is not found!")); } List<string> extensions = this.GetFilterExtensions(filter); List<string> files = new List<string>(); if (extensions.Count > 0) { for (int i = 0; i < extensions.Count; i++) { files.AddRange(this.ArrToList(Directory.GetFiles(directoryPath, extensions[i]))); } } else { files.AddRange(this.ArrToList(Directory.GetFiles(directoryPath))); } return files; } /// <summary> /// 解析文件过滤器 /// </summary> /// <param name="filter">Example:"doc file|*.doc|txt file|*.txt"</param> /// <returns></returns> private List<string> GetFilterExtensions(string filter) { List<string> extensions = new List<string>(); if (String.IsNullOrEmpty(filter) == false) { string[] strArr = filter.Split(new char[] { '|' }); for (int i = 1; i < strArr.Length; i += 2) { string temp = strArr[i]; if (temp.StartsWith("*.") == false) temp = "*." + temp; if (extensions.Contains(temp) == false) extensions.Add(temp); } } return extensions; } /// <summary> /// 将数组转换为List /// </summary> /// <param name="strArr"></param> /// <returns></returns> private List<string> ArrToList(string[] strArr) { List<string> strList = new List<string>(); if (strArr != null && strArr.Length > 0) { for (int i = 0; i < strArr.Length; i++) strList.Add(strArr[i]); } return strList; }