简体   繁体   中英

how I can avoid file creation 2 times, only one file which content should be encoded base64 string

  • I have to loop list of strings and write each string in one line.
  • then I have to encode it as base64 string for it and need to create a file.
  • this file I will share encoded file with other program where upon decode file content should show line by line .

To do this,

  • I am first creating a base file and write content line by line.

  • then I am reading all the bytes of file.

  • then creating a base64 string

  • then write base64 string to a new file and deleting the base file

    var lstStr = new List<string> { "Hello1", "Hello2" }; using (var file = new StreamWriter(@"C:\TEMP\base_file.txt")) { foreach (var str in lstStr) { //need to write data line by line file.WriteLine(str); } } var bytes = File.ReadAllBytes(@"C:\TEMP\base_file.txt"); var base64String = Convert.ToBase64String(bytes); File.WriteAllText(@"C:\TEMP\base64_file.txt", base64String); //delete base file File.Delete(@"C:\TEMP\base_file.txt");

Now how I can avoid file creation 2 times, only one file which content should be encoded base64 string.

And when decode by other app, content should display line by line.

 var file = File.ReadAllText(@"C:\TEMP\base64_file.txt");
            File.WriteAllBytes(@"C:\TEMP\file.txt", Convert.FromBase64String(file));

Hello1

Hello2

Assuming UTF-8 encoding of the string:

byte[] dataAsBytes = System.Text.Encoding.UTF8.GetBytes(String.Join(Environment.NewLine, lstStr));
File.WriteAllText(@"C:\TEMP\base64_file.txt",  Convert.ToBase64String(dataAsBytes));

You can simply use MemoryStream .

This is your code changed to use it:

            var lstStr = new List<string>
            {
                "Hello1", "Hello2"
            };

            var memoryStream = new MemoryStream();

            using (var file = new StreamWriter(memoryStream))
            {
                foreach (var str in lstStr)
                {
                    //need to write data line by line
                    file.WriteLine(str);
                }
            }


            var bytes = memoryStream.ToArray();
            var base64String = Convert.ToBase64String(bytes);
            File.WriteAllText(@"C:\TEMP\base64_file.txt", base64String);

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