如何将数据写入C#中的文本文件?
我不知道如何使用FileStream将数据写入文本文件…来自MSDN:如何将数据写入C#中的文本文件?,c#,C#,我不知道如何使用FileStream将数据写入文本文件…来自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
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();
的文档提供了一个很好的示例。
简而言之,您可以创建一个filestream对象,并使用Encoding.UTF8对象(或您想要使用的编码)将明文转换为字节,您可以在其中使用filestream.write方法。
但是只使用类和File.Append*方法会更容易
编辑:示例
File.AppendAllText("/path/to/file", "content here");
假设您已经拥有数据:
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);
}
(摘自并修改)假设您的数据是基于字符串的,这很有效,并根据您的需要更改了异常处理。确保为TextWriter和StreamWriter引用添加using System.IO 使用System.IO
/// <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());
}
}
//
///将消息写入指定的文件名。
///
///要写的信息。
///要将消息写入的文件名。
公共无效日志消息(字符串消息,字符串文件名)
{
尝试
{
使用(TextWriter tw=新StreamWriter(文件名,true))
{
tw.WriteLine(DateTime.Now.ToString()+“-”+消息);
}
}
catch(Exception ex)//写入日志失败,请向跟踪发送消息,以防有人在侦听。
{
System.Diagnostics.Trace.Write(例如ToString());
}
}
您正在从蓝牙设备恢复哪种类型的数据?激光测距仪的数据可能与FileStream
和文件重复。附录text
在性能方面相当?(即要追加的多行文本)@Flater我不知道具体情况,但通常取决于追加一次还是在循环中,等等。
using (var fs = new FileStream(textFilePath, FileMode.Append))
using (var sw = new StreamWriter(fs))
{
sw.WriteLine("This is the appended line.");
}