Skip to content

Directory.EnumerateFiles fails to trim space on directory name, returns invalid file paths #37212

@IanMercer

Description

@IanMercer

Directory.Enumerate files concatenates the directory name and the found file name but does so without first trimming whitespace off the directory name. So instead of failing with an error or finding nothing it returns invalid file name strings like "C:\ \pagefile.sys" with a back slash, a space and another backslash.

I think the issue is here where it uses the original, untrimmed directory name.

    [Test]
    public void CanFindFilesWithSpaceOnEndOfDirectory()
    {
        string path = "C:\\ ";    // note: this has a space on the end of the path
        var pagefile = System.IO.Directory.EnumerateFiles(path, "pagefile.sys").First();
        pagefile.Should().Be("C:\\pagefile.sys");
    }

Results:

   Expected pagefile to be 
     "C:\pagefile.sys" with a length of 15, but 
     "C:\ \pagefile.sys" has a length of 17, differs near " \p" (index 3).

This is a .NETStandard 2.0 project building on VS 16.6.0 compiling to x64 but I don't think it's specific to that environment.

This test also fails, so maybe this needs fixing in Combine:

        string path = System.IO.Path.Combine("C:\\ ", "pagefile.sys");
        path.Should().Be("C:\\pagefile.sys");

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions