Loading...
 
JoiWiki » Developer » .Net » .Net Snippets » CSharp Append to txt File CSharp Append to txt File

CSharp Append to txt File

C# Append to txt File

 This is a really quick one, mainly because .Net makes this kind of thing really easy!. Here we're making use of the System.IO.StreamWriter class, which has an initialisation that will create the file being asked of it if it doesn't already exist and the boolean parameter denotes whether or not the class is initialised in 'append' mode. 

 

So below are two potential uses of the StreamWriter, the first is a simple method that will append to any file that you pass to it and the second is something that I used for some very quick and very dirty logging (I just wanted a log of command line arguments created in a text file next to the running exe). Do with these as you will!

public static void AppendToTxtFile(string _Path, string _Message)
{
	using (var tw = new System.IO.StreamWriter(_Path, true))
	{
		tw.WriteLine(_Message);
	}
}


public static void AppendToLog(string _Message)
{
	string path = String.Format(@"{0}\ArgsLog.txt", Application.StartupPath);
	using (var tw = new System.IO.StreamWriter(path, true))
	{
		tw.WriteLine(_Message);
	}
}

 

 

 

Created by JBaker. Last Modification: Monday June 24, 2019 14:55:12 BST by JBaker.

Developer