user2143207
user2143207

Reputation: 69

How to append line at end of file using File.Append in C#

I am creating a txt file using c# and writing multiple lines. The problem is that line is getting appended at top and not at end.

Any info on how to achieve this. This is below code

    private static void WriteReleaseSql( string sqlStatement)
    {
        string ReleaseoutputFilePath = ConfigurationManager.AppSettings["ReleaseOutputFilePath"];

        using (FileStream fs = new FileStream(ReleaseoutputFilePath, FileMode.Append, FileAccess.Write))
        using (StreamWriter sw = new StreamWriter(fs))
        {
            sw.WriteLine(sqlStatement);
        }
    }

Upvotes: 1

Views: 1755

Answers (3)

Hadi
Hadi

Reputation: 37368

You can use StreamWriter without FileStream (user instance) and it works fine for me

private static void WriteReleaseSql( string sqlStatement)
{
    string ReleaseoutputFilePath = ConfigurationManager.AppSettings["ReleaseOutputFilePath"];

    using (StreamWriter sw = new StreamWriter(ReleaseoutputFilePath,True))
    {
        sw.WriteLine(sqlStatement);
    }
}

Note: your code works fine

Upvotes: 1

Nothing
Nothing

Reputation: 99

Use Environment.NewLine to add a new line.

Upvotes: -1

Prajwal
Prajwal

Reputation: 4000

When I checked MDSN Website for FileMode,this is the definition I got.

Opens the file if it exists and seeks to the end of the file, or creates a new file. This requires FileIOPermissionAccess. Append permission. FileMode.Append can be used only in conjunction with FileAccess.Write. Trying to seek to a position before the end of the file throws an IOException exception, and any attempt to read fails and throws a NotSupportedException exception.

As far as the doc goes, it should append things at the end. Please check the output again.

I would really like to know how to add things at the top, though.

Upvotes: 1

Related Questions