繁体   English   中英

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

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM