我无法弄清如何使用FileStream将数据写入文本文件...
我无法弄清如何使用FileStream将数据写入文本文件...
假设您已经有了数据:
string path = @"C:\temp\file"; // path to file
using (FileStream fs = File.Create(path))
{
// writing data in string
string dataasstring = "data"; //your data
byte[] info = new UTF8Encoding(true).GetBytes(dataasstring);
fs.Write(info, 0, info.Length);
// writing data in bytes already
byte[] data = new byte[] { 0x0 };
fs.Write(data, 0, data.Length);
}
(从MSDN文档中获取并进行了修改)
使用FileStream的文档提供了一个很好的例子。
简而言之,您需要创建一个文件流对象,并使用Encoding.UTF8对象(或您想要使用的编码方式)将纯文本转换为字节,然后可以使用filestream.write方法进行写入。
但是如果使用File类和File.Append*方法可能更容易些。
编辑:示例
File.AppendAllText("/path/to/file", "content here");
FileStream
和 File.AppendAllText
是否相等?(即附加许多行文本)。 - Flaterusing (var fs = new FileStream(textFilePath, FileMode.Append))
using (var sw = new StreamWriter(fs))
{
sw.WriteLine("This is the appended line.");
}
来自 MSDN:
FileStream fs=new FileStream("c:\\Variables.txt", FileMode.Append, FileAccess.Write, FileShare.Write);
fs.Close();
StreamWriter sw=new StreamWriter("c:\\Variables.txt", true, Encoding.ASCII);
string NextLine="This is the appended line.";
sw.Write(NextLine);
sw.Close();
http://msdn.microsoft.com/en-us/library/system.io.filestream.aspx
/// <summary>
/// Writes a message to the specified file name.
/// </summary>
/// <param name="Message">The message to write.</param>
/// <param name="FileName">The file name to write the message to.</param>
public void LogMessage(string Message, string FileName)
{
try
{
using (TextWriter tw = new StreamWriter(FileName, true))
{
tw.WriteLine(DateTime.Now.ToString() + " - " + Message);
}
}
catch (Exception ex) //Writing to log has failed, send message to trace in case anyone is listening.
{
System.Diagnostics.Trace.Write(ex.ToString());
}
}