Create and write to a text file inmemory and convert to byte array in one go
Write text into 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(ms);
}
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();
}
You can get a byte array from a string using encoding:
Encoding.ASCII.GetBytes(aString);
Or
Encoding.UTF8.GetBytes(aString);
But I don't know why you would want a csv as bytes. You could load the entire file to a string, 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(line);
}
return Encoding.ASCII.GetBytes(stringBuilder.ToString());