Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

File.Exists returns true and OpenExisting fails with DirectoryNotFoundException

Tags:

c#

.net

I am tring to open memory mapped file in the system volume information subfolder. I know and see in explorer that it is exists there, and path is correct (it is copy-pasted from explorer), moreover File.Exists for that path returns true, but MemoryMappedFile.OpenExisting fails with DirectoryNotFoundException. Why? (I have all rights to system volume information folder and subfolders).

Some code:

const string filePath = @"C:\\System Volume Information\\Foo\\2.ext";

bool exists = File.Exists(filePath); //is true
using (MemoryMappedFile bitmapFile = MemoryMappedFile.OpenExisting(filePath, MemoryMappedFileRights.Read)) //Throws DirectoryNotFoundException
{
    ...
}
like image 750
Brans Ds Avatar asked Sep 02 '14 14:09

Brans Ds


People also ask

What is directorynotfoundexception?

The exception that is thrown when part of a file or directory cannot be found. [ System.Serializable ] public class DirectoryNotFoundException : System. IO. IOException [ System.Serializable ] [ System.Runtime.InteropServices.ComVisible (true) ] public class DirectoryNotFoundException : System. IO. IOException

Why does my error message only contain file or directory names?

If your code does not have PathDiscovery permission, the error message for this exception may only contain file or directory names instead of fully qualified paths. Initializes a new instance of the DirectoryNotFoundException class with its message string set to a system-supplied message and its HRESULT set to COR_E_DIRECTORYNOTFOUND.

How do I catch a directory not found error?

Directory.SetCurrentDirectory (dir) Catch ex As System.IO.DirectoryNotFoundException ' Let the user know that the directory did not exist. Console.WriteLine ("Directory not found: " + ex.Message) End Try End Sub End Module

What happens when an exception is overridden in a derived class?

When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. Serves as the default hash function. When overridden in a derived class, sets the SerializationInfo with information about the exception.


2 Answers

You need to use MemoryMappedFile.CreateFromFile("yourPathToFileInDisk", FileMode.Open,"WhateverName") which is opening file you need. MemoryMappedFile.OpenExisting("WhateverName") tries to open already existing memory mapped file.

like image 166
Renatas M. Avatar answered Oct 08 '22 13:10

Renatas M.


I haven't used these APIs, but I believe you need to map the file to memory first. Try MemoryMappedFile.CreateFromFile

like image 42
tdemay Avatar answered Oct 08 '22 13:10

tdemay