Skip to content

Directory.GetFiles() returns file paths with trailing spaces if the directory path has trailing spaces #113120

@pelhu

Description

@pelhu

Description

Issue Description:

When using the Directory.GetFiles() method in C#, if there are trailing spaces in the directory path, the returned file paths also end up containing trailing spaces. This behavior can lead to a "file not found" error when trying to access the files.

Example:

When executing the following code:

var files = Directory.GetFiles(@"C:\folder ");
foreach (var file in files)
{
    Console.WriteLine(file);
}

Actual Result:

C:\folder \doc.pdf

Expected Result:

C:\folder\doc.pdf

Reproduction Steps

  1. Set a directory path with trailing spaces.
  2. Call the Directory.GetFiles() method.
  3. Observe the returned file paths, which contain trailing spaces.
  4. Attempt to access one of the files using the returned path and note the "file not found" error.

Expected behavior

I expected it to give a folder not found error

Actual behavior

The wrong file path is returned and a "file not found" error is encountered.

Regression?

No response

Known Workarounds

Trimming of folder path

Configuration

.NET Version: 8.0
Operating System: Windows 10 x64

Other information

No response

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions