Search code examples
c#.netxmltextreader

Hash character in path throws DirectoryNotFoundException


Consider the following code snippet

private void ProcessFile(string fullPath) {
    XmlTextReader rdr = new XmlTextReader("file:\\\\" + fullPath);
    while (rdr.Read()) {
        //Do something
    }
    return;
}

Now, this functions fine when passed a path like:

"C:\Work Files\Technical Information\Dummy.xml"

But throws an error when passed

"C:\Work Files\#Technical Information\Dummy.xml"

Note that all folders and files specified exist and that the hash character is a valid character for paths. The error details are:

System.IO.DirectoryNotFoundException: Could not find a part of the path 'C:\Work Files\'.
at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy)
at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize)
at System.Xml.XmlDownloadManager.GetStream(Uri uri, ICredentials credentials)
at System.Xml.XmlUrlResolver.GetEntity(Uri absoluteUri, String role, Type ofObjectToReturn)
at System.Xml.XmlTextReaderImpl.OpenUrlDelegate(Object xmlResolver)
at System.Threading.CompressedStack.runTryCode(Object userData)
at System.Runtime.CompilerServices.RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(TryCode code, CleanupCode backoutCode, Object userData)
at System.Threading.CompressedStack.Run(CompressedStack compressedStack, ContextCallback callback, Object state)
at System.Xml.XmlTextReaderImpl.OpenUrl()
at System.Xml.XmlTextReaderImpl.Read()
at System.Xml.XmlTextReader.Read()

Anybody know what's going on?


Solution

  • Try omitting the file:/// protocol prefix. It works for me without one. I believe .NET will truncate any part after the # if it believes this to be a URL. This is only a guess based on the error message but it seems logical considering that the part after the # character isn't processed by the server but rather by the client in other scenarios (e.g. web browsers).