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

34

我无法弄清如何使用FileStream将数据写入文本文件...


你从蓝牙设备接收到了什么类型的数据? - Terrance
激光测距仪的数据 - lk5163
可能是重复的问题,参考 *最简单的读写文件方法*。 - Peter Mortensen
5个回答

56

假设您已经有了数据:

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文档中获取并进行了修改)


15

使用FileStream的文档提供了一个很好的例子。

简而言之,您需要创建一个文件流对象,并使用Encoding.UTF8对象(或您想要使用的编码方式)将纯文本转换为字节,然后可以使用filestream.write方法进行写入。

但是如果使用File类和File.Append*方法可能更容易些。

编辑:示例

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

在性能方面,FileStreamFile.AppendAllText 是否相等?(即附加许多行文本)。 - Flater
@Flater 我不是很确定,但通常这取决于你是一次性添加还是在循环中添加等。 - Yet Another Geek

6
using (var fs = new FileStream(textFilePath, FileMode.Append))
using (var sw = new StreamWriter(fs))
{
    sw.WriteLine("This is the appended line.");
}

4

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


2
假设你的数据是基于字符串的,这个方法很有效,你可以根据需要改变异常处理方式。确保添加using System.IO来引用TextWriter和StreamWriter。
使用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());
            }
        }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接