Curiosity, learning and homework help
21/12/2024
Sign upLog in
Language: FR | ENG

> Back to the home page <

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 05: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 05: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.


You can find more information here:
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 06: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
Share this page on social media:

Use of cookies on this website:
- If you are not a member of this website, no cookie is intentionally stored on your computer.
- If you are a member of this website, cookies are only used to keep your connection after each visit. This option can be deactivated at will in your profile and is deactivated by default.
- No other information is stored or retrieved without your knowledge, neither your personal information nor any other whatsoever. If in doubt, do not hesitate to contact the administrator of this website .
- Even this information banner does not use cookies and will therefore be displayed constantly on each visit on all pages of the website.