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