Create a "directory" in memory?

I work in C # and am looking for a way to create a directory path that will be displayed in IO.Stream, and not in the actual file system.
I want to be able to “save” files to this path, manage the contents or file names, and then save them from this path to a regular file in the file system.

I know I can use a temporary file, but I would prefer to use memory for both security and performance.

This view exists according to this answer , in Java , using FileSystemProvider . I am looking for a way to do this in C #.

I tried every search that I could think of, and came up with only a Java answer and suggestions for using temporary files.
Is this possible with .net?

Basically, I'm looking for a way to enable saving files directly to memory, as if they were saved on a file system. so, for example, if I had a third-party class that provides a save method ( save(string fullPath) ) or something like SmtpServer.Send(MyMsg) in this question , I could select this path and save it in the memory stream, not on disk. (the main thing is that I want to provide a path that will lead directly to a memory stream ).

+6
source share
2 answers

.NET does not have an abstraction layer over the host OS file system. Therefore, if you cannot create your own for use in user code, and you need to have third-party libraries, there are only two operable optilns:

  • Use streams and avoid any API working with file names.
  • Create a virtual file system connected to your host system storage architecture; however, the effort required against the benefits is highly questionable.
+8
source

Recently, I came across a similar situation, and in .NET there was no ready-made solution for this, although I used a workaround that was effective and safe for me.

Using the Ionic.Zip Nuget package, you can create an entire directory with a complex structure in the form of a stream in memory, and although it will be created as a zip file, you can extract it as a stream or even send a zip file as a stream.

  using (var zip = new Ionic.Zip.ZipFile()) { zip.AddEntry($"file1.json", new MemoryStream(Encoding.UTF8.GetBytes(someJsonContent))); for (int i = 0; i < 4; i++) { zip.AddEntry($"{myDir}/{i}.json", new MemoryStream(Encoding.UTF8.GetBytes(anotherJsonContent))); } } 

Here's how to extract a zip file as a stream using Ionic.Zip

0
source

Source: https://habr.com/ru/post/986913/


All Articles