Can you call Directory.GetFiles() with multiple filters?

前端 未结 26 2794
逝去的感伤
逝去的感伤 2020-11-22 05:25

I am trying to use the Directory.GetFiles() method to retrieve a list of files of multiple types, such as mp3\'s and jpg\'s. I have t

26条回答
  •  独厮守ぢ
    2020-11-22 06:08

    I had the same problem and couldn't find the right solution so I wrote a function called GetFiles:

    /// 
    /// Get all files with a specific extension
    /// 
    /// string list of all the extensions
    /// string of the location
    /// array of all the files with the specific extensions
    public string[] GetFiles(List extensionsToCompare, string Location)
    {
        List files = new List();
        foreach (string file in Directory.GetFiles(Location))
        {
            if (extensionsToCompare.Contains(file.Substring(file.IndexOf('.')+1).ToLower())) files.Add(file);
        }
        files.Sort();
        return files.ToArray();
    }
    

    This function will call Directory.Getfiles() only one time.

    For example call the function like this:

    string[] images = GetFiles(new List{"jpg", "png", "gif"}, "imageFolder");
    

    EDIT: To get one file with multiple extensions use this one:

    /// 
        /// Get the file with a specific name and extension
        /// 
        /// the name of the file to find
        /// string list of all the extensions
        /// string of the location
        /// file with the requested filename
        public string GetFile( string filename, List extensionsToCompare, string Location)
        {
            foreach (string file in Directory.GetFiles(Location))
            {
                if (extensionsToCompare.Contains(file.Substring(file.IndexOf('.') + 1).ToLower()) &&& file.Substring(Location.Length + 1, (file.IndexOf('.') - (Location.Length + 1))).ToLower() == filename) 
                    return file;
            }
            return "";
        }
    

    For example call the function like this:

    string image = GetFile("imagename", new List{"jpg", "png", "gif"}, "imageFolder");
    

提交回复
热议问题