Thursday 14 June 2012

.Net Beginners , C# Tips : Append or Write the data to a text file

There is a very quick way to open text file and appends data into that file.
There are two methods to appends text files AppendAllText and AppendAllLines.
These methods open a file. Appends data to the files , and then close the file. If file does not exist, These methods create the files , appends the data and close the file.

If you do not want append the data but you want overwrite the data of file you can also do this with the help of WriteAllText and WriteAllLines Methods.
These methods create the file and write data in file, If file is already exists than this will overwrite data.

Here are sample example of this.
In this example For append we are using AppendAllText method for directly append sample string.
and  AppendAllLines method to append IEnumerable of strings.
For write we are using WriteAllText method to write data in file and WriteAllLines method to write IEnumerable of strings.

C# Example :
    string strData = "This is sample string.";

    string[] lineNumbers = (from line in System.IO.File.ReadLines(MapPath("TextFile.txt"))
                            where line.Contains("sample")
                            select line).ToArray();

    // Appends the string of data to a file
    System.IO.File.AppendAllText(MapPath("TextFile1.txt"), strData);
    //Appends the IEnumerable of strings to a text file
    System.IO.File.AppendAllLines(MapPath("TextFile1.txt"), lineNumbers);

    // Writes the string of data to a file
    System.IO.File.WriteAllText(MapPath("TextFile2.txt"), strData);

    // Writes an IEnumerable of strings to a text file
    System.IO.File.WriteAllLines(MapPath("TextFile2.txt"), lineNumbers);

VB.net Example :
        Dim strData As String = "This is sample string."

        Dim lineNumbers As String() = (From line In System.IO.File.ReadLines(MapPath("TextFile.txt"))
                                      Where line.Contains("sample")
                                      Select line).ToArray()

        ' Appends the string of data to a file
        System.IO.File.AppendAllText(MapPath("TextFile1.txt"), strData)
        'Appends the IEnumerable of strings to a text file
        System.IO.File.AppendAllLines(MapPath("TextFile1.txt"), lineNumbers)

        ' Writes the string of data to a file
        System.IO.File.WriteAllText(MapPath("TextFile2.txt"), strData)

        ' Writes an IEnumerable of strings to a text file
        System.IO.File.WriteAllLines(MapPath("TextFile2.txt"), lineNumbers)

This is very useful .Net Tips which is use in day to day programming life.


No comments:

Post a Comment