Create and write to inmemory text file and convert to byte array at a time

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?

+11
source share
2 answers

Enter text into the memory stream.

 byte[] bytes = null; using (var ms = new MemoryStream()) { TextWriter tw = new StreamWriter(ms); tw.Write("blabla"); tw.Flush(); ms.Position = 0; bytes = ms.ToArray(); //or save to disk using FileStream (fs) ms.WriteTo(fs); } 

UPDATE

Use File Stream Directly

  using (var fs = new FileStream(@"C:\sh\test.csv", FileMode.Create, FileAccess.ReadWrite)) { TextWriter tw = new StreamWriter(fs); tw.Write("blabla"); tw.Flush(); } 
+13
source

You can get a byte array from a string using the encoding:

 Encoding.ASCII.GetBytes(aString); 

Or

 Encoding.UTF8.GetBytes(aString); 

But I do not know why you would like CSV as bytes. You can load the entire file into a line, add to it, and then save it:

 string content; using (var reader = new StreamReader(filename)) { content = reader.ReadToEnd(); } content += "x,y,z"; using (var writer = new StreamWriter(filename)) { writer.Write(content); } 

Update: create a CSV in memory and pass back as bytes:

 var stringBuilder = new StringBuilder(); foreach(var line in GetLines()) { stringBuilder.AppendLine(log); } return Encoding.ASCII.GetBytes(stringBuilder.ToString()); 
+7
source

Source: https://habr.com/ru/post/1247250/


All Articles