Curiosity, learning and homework help
28/11/2021
Language: FR | ENG

Discussion forums

[C#] Write data in a file
You have to be logged in to reply
Author Message
BGjohn

Member
Posted on 13/11/2021 at 00:21:08

by BGjohn
Member
Hi!

I am writing a program in C# and I am looking for creating a text file and writing data in this file during the execution. I also don't want the program to overwrite the file. I want the data to be written at the end of an existing file.

Can you help to find the correct function to do that?
Thanks!
TheLibrarian

**Moderator**
Posted on 13/11/2021 at 00:54:17

by TheLibrarian
**Moderator**
Hello BGjohn! 🙂

In C#, to write in a file without overwrite it, you can use the class StreamWriter.
And do not forget to use the namespace System.IO.

Here is the syntax:

using System.IO;

StreamWriter file = new StreamWriter(@"C:\filename.txt", true); //open the file (and create it if it does not already exist)
//true means not to overwrite the file but to write at the end of the existing file

file.WriteLine("The text to write."); //write text to the file.

file.Close(); //close the file.

https://docs.microsoft.com/en-us/dotnet/api/system.io.streamwriter.-ctor?view=net-5.0#System_IO_StreamWriter__ctor_System_String_System_Boolean_

Please let me know if you need more help. 😉
Good luck!
--------------------------
BGjohn

Member
Posted on 13/11/2021 at 01:14:43

by BGjohn
Member
Thank you very much. This is exactly what I was looking for. 🙂
You have to be logged in to reply