Search code examples
c#file-iounc

File.OpenRead() throws UnauthorizedAccessException when a directory with same path exists


When invoking File.OpenRead() on a file on a network share where a folder with the same name (but different casing) exists, UnauthorizedAccessException. This can happen on Linux shares where casing matters.

Example: * P: is mapped to \somemachine\someshare * P:\files\ is a folder * P:\files\OUTPUT is a file * P:\files\output is a folder

The following code will throw:

const string path = @"P:\files\OUTPUT";

DirectoryInfo dir = new DirectoryInfo(Path.GetDirectoryName(path));
FileInfo file = dir.EnumerateFiles().FirstOrDefault(x => string.Equals(Path.GetFileName(path), x.Name));

// All of the below throws UnauthorizedAccessException            
file.OpenRead(); 
FileStream stream = new FileStream(file.FullName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
File.OpenRead(path);

Is there any way I can open the file case sensitively? It's not an option to rename the file or move the folder out of the way as this is a read only share.


Solution

  • That's the default SAMBA behaviour:

    That which is lexically first will be accessible to MS Windows users; the others are invisible and unaccessible any other solution would be suicidal.

    The only safe option is to use different names for the folder and file. Trying to ensure that one or the other is lexically first is (per the docs) ... suicidal.

    EDIT

    From the comments, it appears that Notepad can open the correct file. Despite its simplistic look, Notepad does a lot of work to handle complex cases, like detecting a file's when no BOM is available.

    It may also be using long Unicode paths (eg \\?\P:\files\OUTPUT) to access files, alternate streams and shares, or it may be detecting that a network volume is in use and switch to the long path format.

    System.IO doesn't support this as it's NTFS specific, but the the open-source AlphaFS provides access to this and a LOT of other useful NTFS functionality like transactions and Object IDs.

    You may be able to use AlphaFS to open the file using a long path, although I haven't tried this.