Roald
Roald

Reputation: 2999

Inconsistent behavior of Directory.EnumerateFiles between .NET Core and .NET Framework

I have a project which contains two files: book.xls and book.xlsx. If I run the following code (on .NET Framework) it finds both files as expected, despite only passing .xls as extension.

using System;
using System.IO;
using System.Linq;

namespace GetFilesFromExtensionsWithTests
{
    public class Program
    {
        static void Main(string[] args)
        {
            var filesWithExtension = FindFiles("../../", "*.xls");
            foreach (string file in filesWithExtension)
            {
                Console.WriteLine($"Found: {file}");
                // Found: ../../ book.xls
                // Found: ../../ book.xlsx
            }
            Console.ReadKey();
        }

        static public string[] FindFiles(string path, string extension)
        {
            var files = Directory.EnumerateFiles(path, extension).Select(p => p).ToArray();

            return files;
        }
    }
}

This is expected behavior: when you pass a three character extension to Directory.EnumerateFiles it will find all extensions which start with xls (docs):

When you use the asterisk wildcard character in a searchPattern such as "*.txt", the number of characters in the specified extension affects the search as follows:

  • If the specified extension is exactly three characters long, the method returns files with extensions that begin with the specified extension. For example, "*.xls" returns both "book.xls" and "book.xlsx".

The strange thing is that if I run FindFiles from an xUnit project (.NET Core) it only finds book.xls:

using GetFilesFromExtensionsWithTests;
using Xunit;

namespace GetFilesFromExtensionsWithTests_Tests
{
    public class UnitTest1
    {
        [Fact]
        public void Test1()
        {
            string[] files = Program.FindFiles(
                @"..\..\..\..\FileExtensionsWithTests", "*.xls"
            );

            // Test fails, because it only finds book.xls, but not book.xlsx
            Assert.Equal(2, files.Length);
        }
    }
}

Why is there a difference?

Edit 14 September 2020

It's a known issue https://github.com/dotnet/dotnet-api-docs/issues/4052

Upvotes: 1

Views: 189

Answers (1)

Roald
Roald

Reputation: 2999

It's a known issue which is reported at https://github.com/dotnet/dotnet-api-docs/issues/4052

Upvotes: 1

Related Questions