Home > Mobile >  Create a directory in memory and save some files using C#
Create a directory in memory and save some files using C#

Time:08-26

I am a noob to C#.

So, needed a small help from stackoverflow community.

I want to create a directory structure in memory (not storage device) and place some files into it (for security and faster access purpose).

Later some other process/method wants to access these directories and read the files. I think this can be achieved with some memory buffer, but I'm not able to implement it in C#.

Please help !

Thanks in advance.

CodePudding user response:

You cannot write files to the file-system without actually writing them to a storage device. Note that there are ram-drives that act as storage devices, while keeping the files in memory.

If you just want to lookup some data by a string-key you can just use a Dictionary<string, MemoryStream>, and while it would be difficult to make access much faster, the data would only be accessible from your process. Another option could be a zip-archive, that kind of works like a dictionary, but also compresses the contents.

I'm really unsure what you mean with "security", whenever talking about security you really need to define what kind of threat you want to protect against. Writing data to disk does not automatically makes it more secure, if anything it would be made less secure since it is much easier to read data from disk than from memory of another process.

CodePudding user response:

you can check this piece of code and modify as you require.

[HttpPost]
public IActionResult Upload(SingleFileModel model)
{
if (ModelState.IsValid)
{
    model.IsResponse = true;

    string path = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot/Files");

    //create folder if not exist
    if (!Directory.Exists(path))
        Directory.CreateDirectory(path);

    //get file extension
    FileInfo fileInfo = new FileInfo(model.File.FileName);
    string fileName = model.FileName   fileInfo.Extension;

    string fileNameWithPath = Path.Combine(path, fileName);

    using (var stream = new FileStream(fileNameWithPath, FileMode.Create))
    {
        model.File.CopyTo(stream);
    }
    model.IsSuccess = true;
    model.Message = "File upload successfully";
}
  • Related