如何在C#中将数据写入文本文件?

我无法弄清楚如何使用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 docs并修改)

FileStream的文档提供了一个很好的例子。 简而言之,您创建一个文件流对象,并使用Encoding.UTF8对象(或您要使用的编码)将您的明文转换为字节,您可以在其中使用您的filestream.write方法。 但是使用File类和File.Append *方法会更容易。

编辑 :示例

  File.AppendAllText("/path/to/file", "content here"); 

以下代码摘自http://visualcsharptutorials.com/2011/02/writing-to-a-text-file/,但应该让您了解如何使用FileStream编写代码。

 using System; using System.IO; using System.Text; namespace WritingToFile { class Program { static void Main() { FileStream fs = new FileStream("sample.txt", FileMode.Create); StreamWriter writer = new StreamWriter(fs); StringBuilder output = new StringBuilder(); int repeat = 0; do { Console.WriteLine("Please enter first name: "); output.Append(Console.ReadLine() + "#"); Console.WriteLine("Please enter last name: "); output.Append(Console.ReadLine() + "#"); Console.WriteLine("Please enter age: "); output.Append(Console.ReadLine()); writer.WriteLine(output.ToString()); output.Clear(); Console.WriteLine("Repeat? 1-Yes, 0-No : "); repeat = Convert.ToInt32(Console.ReadLine()); } while (repeat != 0); writer.Close(); } } } 

来自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

假设您的数据是基于字符串的,这很有效,您可以根据需要更改exception处理。 确保为TextWriter和StreamWriter引用添加使用System.IO。

使用System.IO;

  ///  /// Writes a message to the specified file name. ///  /// The message to write. /// The file name to write the message to. 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()); } }