Curiosité, apprentissage et soutien scolaire
29/06/2022
InscriptionConnexion
Langue : FR | ENG

> Retour sur la page d'accueil <

Forums de discussion

[C#] Write data in a file
Vous devez être connecté pour répondre
Auteur Message
BGjohn

Membre
Posté le 13/11/2021 à 00:21:08

de BGjohn
Membre
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

**Modérateur**
Posté le 13/11/2021 à 00:54:17

de TheLibrarian
**Modérateur**
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

Membre
Posté le 13/11/2021 à 01:14:43

de BGjohn
Membre
Thank you very much. This is exactly what I was looking for. 🙂
Vous devez être connecté pour répondre