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

时间:2011-05-27 13:43:36

标签: c#

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

5 个答案:

答案 0 :(得分:29)

假设您已有数据:

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并修改)

答案 1 :(得分:10)

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

编辑:示例

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

答案 2 :(得分:2)

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

答案 3 :(得分:1)

假设您的数据是基于字符串的,这很有效,您可以根据需要更改异常处理。确保为TextWriter和StreamWriter引用添加使用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());
            }
        }

答案 4 :(得分:-1)

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