How do I write data to a text file in C#?

From 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


Assuming you have the data already:

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);
}

(taken from msdn docs and modified)


Assuming your data is string based, this works well, changed your exception handling as you see fit. Making sure add a using System.IO for TextWriter and StreamWriter references.

using 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());
            }
        }

The documentation for FileStream gives an excellent example. In short you create a filestream object, and use the Encoding.UTF8 object (or the encoding you want to use) to convert your plaintext to bytes, in which you can use your filestream.write method. But it would be easier to just use the File class, and File.Append* methods.

EDIT: Example

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

Tags:

C#