Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing a text file in memory without storing to disk

Tags:

c#

.net

I have a list of string as input, which I need to put into a text file, and then put that text file into an encrypted ZIP archive. I want to do this in two steps:

  1. Create a text file and get its bytes
  2. Write the bytes into the archive using a zip library

However, there is one main requirement: For security reasons I am not allowed to write the text file to disk!

I've been playing around with memory streams and stream writers etc. but can't seem to figure it out. I'd prefer UTF8 encoding.

private byte[] GenerateTextFile(List<string> contents)
{
    // Generate a text file in memory and return its bytes
}

Can you guys help me out?

like image 365
Bart van der Drift Avatar asked Aug 31 '25 16:08

Bart van der Drift


1 Answers

That's an easy one, you should concat all the strings into one and then call Encoding.UTF8.GetBytes()

To concat the strings you can use:

string.Join(delimiter, contents)

If you don't need the delimeter just remove it, otherwise you probably need to use a \n

So you would have this method:

private byte[] GenerateTextFile(List<string> contents)
{
    return Encoding.UTF8.GetBytes(string.Join(delimiter, contents));
}
like image 105
Ignacio Soler Garcia Avatar answered Sep 02 '25 05:09

Ignacio Soler Garcia