Represent a memory stream as a physical file

Today I ran into some kind of stupid problem:

In my project I have to use a library (which I cannot replace), the problem is that I use a MemoryStream instead of saving it to the HDD often (because there are a lot of files and they are small in size, so it is ideal for a MemoryStream ). The problem is that the library API is built on access to the file system - and one of the functions accepts only the direct path to the file.

How can I send a string (path) to a method that makes a new FileStream without touching the hard drive?

For example, "\ MEMORY \ myfile.bin"?

+4
source share
4 answers

Good - that thought.
Basically, you have three possible solutions:

  • You can use reflector to modify the provided library.
  • You can test the appropriate method, and then using reflection magic, you can change the object at runtime (highly discouraged).
  • You can play with system calls and APIs, and by switching to the low-level assembly of ring0, change kernal.dll to I / O requests to redirect from your path to memory. (perhaps this is possible without calling ring0 - I'm not sure).

Obviously, the most recommended is to use a reflector to modify the provided library. otherwise, I do not see a solution for you.

In response to the first comment, you can:
use RAMDrive (a program that allocates small fragments of system memory and shows it as a partition)

+1
source

If the file must exist on the disk (and only paths to the disk are accepted), then the main option is a virtual file system, which allows you to publish user data in the form of a file system. There are several options, such as the now dead Dokan, our version of Solid File System OS and the callback file system (see the description of our Virtual Storage line) and perhaps the Pismo File Mount will work (never looked at it).

+1
source

It all depends on how the library is built.

If it's a 100% managed library that uses FileStream , you're probably stuck.

If it accepts the provided file name and calls its own WIN32 CreateFile function, it can give it something other than a file, such as a named pipe.

To quickly test, if possible, go @"\\.\pipe\random_name" to the method: if it answers, stating directly that it cannot open channels and file names starting with \\.\ , Well, sorry. On the other hand, if he says that he cannot find the file, you have a chance to make it work.

You can then create a NamedPipeServerStream and use the same name to invoke the library method added with \\.\pipe\ .

+1
source

You cannot โ€œpresentโ€ it as a file, but you can โ€œconvertโ€ it to a file using the StreamWriter class.

0
source

All Articles