如何使用正确的方法隐式/自动创建.csv文件,将文本添加到内存中现有的文件中,然后将内存中的数据转换为字节数组?
string path = @"C:\test.txt";
File.WriteAllLines(path, GetLines());
byte[] bytes = System.IO.File.ReadAllBytes(path);
使用这种方法,我总是(良好)创建一个文件,将其写入(良好),然后将其关闭(不良),然后从路径再次打开该文件,然后从硬盘读取(不良)
我该如何改善呢?
更新
一种几乎不错的方法是:
using (var fs = new FileStream(@"C:\test.csv", FileMode.Create, FileAccess.ReadWrite))
{
using (var memoryStream = new MemoryStream())
{
fs.CopyTo(memoryStream );
return memoryStream .ToArray();
}
}
但我无法将文本写入该文件流...仅字节...
更新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();
}
}
}
字符串消息不会持久保存到test.csv文件中。有人知道为什么吗?
将文本写入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);
}
更新
直接使用文件流
using (var fs = new FileStream(@"C:\sh\test.csv", FileMode.Create, FileAccess.ReadWrite))
{
TextWriter tw = new StreamWriter(fs);
tw.Write("blabla");
tw.Flush();
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句