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

Open
#113,120 1 comment 1 reaction 1 assignee View on GitHub

Nobody has claimed this yet.

Assessment

This issue has not been assessed yet.

Description

area-System.IO os-windows
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

Dominant language
C#
Stars
18.3k
Forks
5.6k
PR merge metrics
PR metrics pending

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from dotnet/runtime

All issues in dotnet/runtime

Similar issues

More C# issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.