Bart van der Drift
Bart van der Drift

Reputation: 1336

Writing a text file in memory without storing to disk

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?

Upvotes: 4

Views: 3223

Answers (1)

Ignacio Soler Garcia
Ignacio Soler Garcia

Reputation: 21855

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));
}

Upvotes: 8

Related Questions