[英]How do I write data to a text file in 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 文檔並修改)
FileStream的文檔給出了一個很好的例子。 簡而言之,您創建一個文件流 object,並使用 Encoding.UTF8 object(或您要使用的編碼)將您的純文本轉換為字節,您可以在其中使用您的 filestream.write 方法。 但是使用File class 和 File.Append* 方法會更容易。
編輯:示例
File.AppendAllText("/path/to/file", "content here");
來自 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
假設您的數據是基於字符串的,這很好用,改變了您認為合適的異常處理。 確保為 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());
}
}
using (var fs = new FileStream(textFilePath, FileMode.Append))
using (var sw = new StreamWriter(fs))
{
sw.WriteLine("This is the appended line.");
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.