简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM