File.AppendAllText(String, String) is an inbuilt File class method which is used to append the specified string to the given file if that file exists else creates a new file and then appending is done. It also closes the file.
public static void AppendAllText (string path, string contents);
Parameter: This function accepts two parameters which are illustrated below:
- path: This is the file where given contents are going to be appended.
- contents: This is the specified contents which is to be appended to the file.
- ArgumentException: The path is a zero-length string, contains only white space, or one or more invalid characters as defined by InvalidPathChars.
- ArgumentNullException: The path is null.
- PathTooLongException: The given path, file name, or both exceed the system-defined maximum length.
- DirectoryNotFoundException: The given path is invalid i.e, the directory doesn’t exist or it is on an unmapped drive.
- IOException: An I/O error occurred while opening the file.
- UnauthorizedAccessException: The path specified a file that is read-only. OR this operation is not supported on the current platform. OR the path specified a directory. OR the caller does not have the required permission.
- NotSupportedException: The path is in an invalid format.
- SecurityException: The caller does not have the required permission.
Below are the programs to illustrate the File.AppendAllText(String, String) method.
Program 1: Before running the below code, a file is created with some contents shown below:
mcs -out:main.exe main.cs mono main.exe GeeksforGeeks is a CS portal.
After running the above code, above output is shown and the file contents become like shown below:
Program 2: Initially no file is created but the below code itself creates a new file and appends the specified contents.
mcs -out:main.exe main.cs mono main.exe GFG is a CS portal.
After running the above code, above output has been shown and a new file created which is shown below:
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.