I need to add text (not a line) to an existing text file, using C#. I can create the file, and write text to it, but when I have to append text, for some reason, it fails. I can append a line, but I don't need to append a line. I just need to append some text. I am passing a boolean to force the creation of a new file the first time it runs. I am also passing the filepath, and the text to be appended. Code is listed below.
NOTE: commented code are all of the different attempts that failed:

public static void FileWriter(string filePath, string text, bool fileExists)
{
    if (!fileExists)
   {
      //StreamWriter SW;
      //SW = File.CreateText(filePath);
      //SW.Write(text);
      //SW.Close();
      FileStream aFile = new FileStream(filePath, FileMode.Create, FileAccess.Write);
      StreamWriter sw = new StreamWriter(aFile);
      sw.Write(text);
      sw.Close();
      aFile.Close();
   }
   else
   {
       //StreamWriter sw = File.AppendText(filePath);
       //sw.Write(text);
       //sw.Flush();
       //sw.Close();
       //StreamWriter SW;
       //SW = File.AppendText(filePath);
       //SW.WriteLine(text);
       //SW.Close();

       FileStream aFile = new FileStream(filePath, FileMode.Append, FileAccess.Write);
       StreamWriter sw = new StreamWriter(aFile);
       sw.Write(text);
       sw.Close();
       aFile.Close();

       //System.IO.File.WriteAllText(filePath, text);
   }
 }

Recommended Answers

All 11 Replies

I don't understand the problem. File.AppendAllText() creates a file if it does not exist and appends the text (not a line).

This code will append the text, create the file if needed, and display the output after each write.

using System;
using System.Diagnostics;
using System.IO;
using System.Windows.Forms;

namespace daniweb
{
  public partial class frmFile : Form
  {
    public frmFile()
    {
      InitializeComponent();
    }

    public static void AppendText(string FileName, string Buffer)
    {
      //I'm using another method here in case you want to log writes etc. 
      //It encapsulates the write process
      File.AppendAllText(FileName, Buffer);
    }

    private void button1_Click(object sender, EventArgs e)
    {
      const string fName = @"C:\file3.txt";
      string buffer = Guid.NewGuid().ToString(); //junk data
      AppendText(fName, buffer);
      Process p = Process.Start("notepad.exe", fName);
      p.WaitForExit();
    }
  }
}

I don't understand the problem. File.AppendAllText() creates a file if it does not exist and appends the text (not a line).

This code will append the text, create the file if needed, and display the output after each write.

using System;
using System.Diagnostics;
using System.IO;
using System.Windows.Forms;

namespace daniweb
{
  public partial class frmFile : Form
  {
    public frmFile()
    {
      InitializeComponent();
    }

    public static void AppendText(string FileName, string Buffer)
    {
      //I'm using another method here in case you want to log writes etc. 
      //It encapsulates the write process
      File.AppendAllText(FileName, Buffer);
    }

    private void button1_Click(object sender, EventArgs e)
    {
      const string fName = @"C:\file3.txt";
      string buffer = Guid.NewGuid().ToString(); //junk data
      AppendText(fName, buffer);
      Process p = Process.Start("notepad.exe", fName);
      p.WaitForExit();
    }
  }
}

Your routine works fine, but the first time the program runs, if the file already exists, I need to overwrite the file, and create a new one. That is the reason I pass the boolean flag to my routine. I tried to add your code to my method, and I had the same error. Can you recommend a way to create a new file + write text the first time, and to append text (NOTE: not to append a line) to the existing file, thereafter. Thanks.

have a look at the attached.

Hi Serkan:
Thanks for the zip files, but I was not able to unzip them (not sure why). Are there any special instructions? I tried doing a backup, and I tried skipping the backup, and either way, I was not able to read/run anything.

I added some modifications to Scott code

using System;
using System.Diagnostics;
using System.IO;
using System.Windows.Forms;

namespace daniweb
{
  public partial class frmFile : Form
  {
    public frmFile()
    {
      InitializeComponent();
    }

    public static void AppendText(string FileName, string Buffer)
    {
      //I'm using another method here in case you want to log writes etc. 
      //It encapsulates the write process
      File.WriteAllText(FileName, Buffer);
    }

    private void button1_Click(object sender, EventArgs e)
    {
      const string fName = @"C:\file3.txt";
      string buffer = Guid.NewGuid().ToString(); //junk data
      AppendText(fName, buffer);
      Process p = Process.Start("notepad.exe", fName);
      p.WaitForExit();
    }
  }
}

Never mind Sknake:
I finally figured out what I was doing wrong. Your solution added to my code works perfectly. Thanks for the help!!

I'm glad you found a solution and good luck!

Please mark this thread as solved if your question has been answered.

Never mind Sknake:
I finally figured out what I was doing wrong. Your solution added to my code works perfectly. Thanks for the help!!

join our request for making sknake a featured poster then.(go to geeks lounge and you will see the thread "congritulations...", add something to support us)

i dont know what is wrong with the attachment that you couldnt open. maybe i have to set some password since our company does something when you attach something without a password which i think salts the contents or so.

Great Help for everyone....

how can i save different data to text file separated by commas and the text file shoul handle 5 records

Hi Ajay 9, welcome to DaniWeb!
Please post your question in a thread on his own, not at the end of a solved thread from 4 years ago.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.