33

I can't figure out how to use FileStream to write data to a text file...

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
lk5163
  • 361
  • 1
  • 3
  • 5

5 Answers5

54

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)

NickAldwin
  • 11,584
  • 12
  • 52
  • 67
15

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");
Yet Another Geek
  • 4,251
  • 1
  • 28
  • 40
  • Are `FileStream` and `File.AppendAllText` equivalent in terms of performance? (i.e many lines of text to be appended) – Flater Oct 23 '17 at 08:28
  • @Flater I do not know specifically, but usually it depends on whether you are appending once or in a loop, etc. – Yet Another Geek Oct 24 '17 at 08:43
6
using (var fs = new FileStream(textFilePath, FileMode.Append))
using (var sw = new StreamWriter(fs))
{
    sw.WriteLine("This is the appended line.");
}
Vedran
  • 10,369
  • 5
  • 50
  • 57
4

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

mdm
  • 12,480
  • 5
  • 34
  • 53
2

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());
            }
        }
Jon Raynor
  • 3,804
  • 6
  • 29
  • 43