File.AppendText() Method in C# with Examples
Last Updated :
20 Jun, 2021
File.AppendText() is an inbuilt File class method which is used to create a StreamWriter that appends UTF-8 encoded text to an existing file else it creates a new file if the specified file does not exist.
Syntax:
public static System.IO.StreamWriter AppendText (string path);
Parameter: This function accepts a parameter which is illustrated below:
- path: This is the file where UTF-8 encoded texts are going to be appended. The file is created if it doesn’t already exist.
Exceptions
- UnauthorizedAccessException: The caller does not have the required permission.
- ArgumentException: The path is a zero-length string, contains only white space, or contains 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.
- NotSupportedException: The path is in an invalid format.
Return Value: Returns a stream writer that appends specified UTF-8 encoded texts to the specified file or to a new file.
Below are the programs to illustrate the File.AppendText() method.
Program 1: Before running the below code, a file file.txt is created with some contents which is shown below:
CSharp
using System;
using System.IO;
class GFG {
public static void Main()
{
string myfile = @"file.txt" ;
using (StreamWriter sw = File.AppendText(myfile))
{
sw.WriteLine( "Gfg" );
sw.WriteLine( "GFG" );
sw.WriteLine( "GeeksforGeeks" );
}
using (StreamReader sr = File.OpenText(myfile))
{
string s = "" ;
while ((s = sr.ReadLine()) != null ) {
Console.WriteLine(s);
}
}
}
}
|
Executing:
mcs -out:main.exe main.cs
mono main.exe
Geeks
Gfg
GFG
GeeksforGeeks
After running the above code, above output is shown and the existing file file.txt becomes like below:
Program 2: Initially, no file is created and hence below code itself create a file named as file.txt
CSharp
using System;
using System.IO;
class GFG {
public static void Main()
{
string myfile = @"file.txt" ;
if (!File.Exists(myfile)) {
using (StreamWriter sw = File.CreateText(myfile))
{
sw.WriteLine( "GeeksforGeeks" );
sw.WriteLine( "is" );
sw.WriteLine( "a" );
}
}
using (StreamWriter sw = File.AppendText(myfile))
{
sw.WriteLine( "computer" );
sw.WriteLine( "science" );
sw.WriteLine( "portal." );
}
using (StreamReader sr = File.OpenText(myfile))
{
string s = "" ;
while ((s = sr.ReadLine()) != null ) {
Console.WriteLine(s);
}
}
}
}
|
Executing:
mcs -out:main.exe main.cs
mono main.exe
GeeksforGeeks
is
a
computer
science
portal.
After running the above code, a new file file.txt is created which is shown below:
Share your thoughts in the comments
Please Login to comment...