How can I create a .csv file implicitly / automatically using the correct method, add text to this file that exists in memory, and then convert the data in memory to an array of bytes?
string path = @"C:\test.txt"; File.WriteAllLines(path, GetLines()); byte[] bytes = System.IO.File.ReadAllBytes(path);
With this approach, I always create a file (good), write to it (good), then close it (bad), then open the file again from the path and read it from the hard drive (bad)
How can I improve this?
UPDATE
One very good approach:
using (var fs = new FileStream(@"C:\test.csv", FileMode.Create, FileAccess.ReadWrite)) { using (var memoryStream = new MemoryStream()) { fs.CopyTo(memoryStream ); return memoryStream .ToArray(); } }
but I cannot write text to this file ... just bytes ...
UPDATE 2
using (var fs = File.Create(@"C:\temp\test.csv")) { using (var sw = new StreamWriter(fs, Encoding.Default)) { using (var ms = new MemoryStream()) { String message = "Message is the correct ÀÀüâ Pi(\u03a0), and Sigma (\u03a3)."; sw.Write(message); sw.Flush(); fs.CopyTo(ms); return ms.ToArray(); } } }
The string message is not saved in the test.csv file. Does anyone know why?
source share