Question

FileInfo behaves differently on .NET 2 and .NET 4.8

I have converted a legacy application from .NET 2 to .NET 4.8 and found that the FileInfo API behaves differently on the 2 platforms.

.NET 2:

new FileInfo("C:\a \b").FullName -> "C:\a\b"

.NET 4.8:

new FileInfo("C:\a \b").FullName -> "C:\a \b"

I am wondering if there is any configuration that I can set in app.config/web.config to make .NET 4.8 behave similar to .NET 2.0?

BTW I also find that on both .NET versions, Directory.CreateDirectory will always ignore the spaces at the end such that Directory.CreateDirectory("C:\a ") will create the folder C:\a.

Could anyone please point me to the corresponding reference of this behavior?

 3  43  3
1 Jan 1970

Solution

 2

You can get .net2 behavior by specifying the following item in the app.config file:

<configuration>
    <runtime>
        <AppContextSwitchOverrides value="Switch.System.IO.UseLegacyPathHandling=true" />
    </runtime>
</configuration>

Although Windows does not recommend adding trailing or leading spaces or periods in file names. You can find a warning here.

You should never create a directory or filename with a trailing space. Trailing spaces can make it difficult or impossible to access a directory, and applications commonly fail when attempting to handle directories or files whose names include trailing spaces.

2024-07-19
shingo