FileIOPermission bug with "Illegal characters in path" and \\?\ prefixes

From: Bill Menees (Bill_at_NoSpam.com)
Date: 11/11/04


Date: Thu, 11 Nov 2004 13:43:20 -0600

FileIOPermission always treats '?' as an illegal character, but \\?\ is a
valid prefix for file names that are using the Unicode API.

As of XP SP2, now the aspnet_wp.exe worker process gets launched with a path
like: \\?\c:\WINDOWS\Microsoft.NET\Framework\v1.1.4322\aspnet_wp.exe. When
a web service calls System.Windows.Forms.Application.StartupPath, it will
throw an exception with a stack trace similar to the following:

System.ArgumentException: Illegal characters in path.
at
System.Security.Permissions.FileIOPermission.HasIllegalCharacters(String[]
str)
at
System.Security.Permissions.FileIOPermission.AddPathList(FileIOPermissionAccess
access, String[] pathListOrig, Boolean checkForDuplicates, Boolean
needFullPath, Boolean copyPathList)
at System.Security.Permissions.FileIOPermission..ctor(FileIOPermissionAccess
access, String path)
at System.Windows.Forms.Application.get_StartupPath()
When the FileIOPermission constructor checks that path, it throws the
ArgumentException due to the question mark character. But it shouldn't do
that. It needs to be smart enough to strip off the valid \\?\ prefix like
the Windows file API methods do.

Application.StartupPath internally calls the GetModuleFileName API. Look at
GetModuleFileName's docs in MSDN. It explicitly states that it can return
paths that are prefixed with \\?\.

Hopefully, Microsoft will fix this bug in .NET 2.0 (or .NET 1.1 SP2). For
now I've created my own Utilities.StartupPath property. It does a DllImport
on GetModuleFileName, and it strips off the \\?\ prefix if necessary.

I wanted to post this here so (1) someone from Microsoft might see it and do
something about it and (2) so other people searching for a workaround can
find one. I spent a non-trivial amount of time tracking this down.

Bill Menees