La finalització d'un programa comporta l'eliminació de totes les dades relacionades amb ell. Per tant, hem d'emmagatzemar les dades en algun lloc. Els fitxers s'utilitzen per emmagatzemar i compartir dades de manera permanent. C# es pot utilitzar per recuperar i manipular dades emmagatzemades en fitxers de text.
Lectura d'un fitxer de text: La classe de fitxer en C# defineix dos mètodes estàtics per llegir un fitxer de text, és a dir File.ReadAllText() i File.ReadAllLines() .
- File.ReadAllText() llegeix tot el fitxer alhora i retorna una cadena. Hem d'emmagatzemar aquesta cadena en una variable i utilitzar-la per mostrar el contingut a la pantalla.
- File.ReadAllLines() llegeix un fitxer una línia a la vegada i retorna aquesta línia en format de cadena. Necessitem una matriu de cadenes per emmagatzemar cada línia. Mostrem el contingut del fitxer utilitzant la mateixa matriu de cadenes.
Hi ha una altra manera de llegir un fitxer i és mitjançant un objecte StreamReader. El StreamReader també llegeix una línia a la vegada i retorna una cadena. Totes les maneres esmentades anteriorment de llegir un fitxer s'il·lustren al codi d'exemple que es mostra a continuació.
// C# program to illustrate how> // to read a file in C#> using> System;> using> System.IO;> > class> Program {> >static> void> Main(>string>[] args)> >{> >// Store the path of the textfile in your system> >string> file =>@'M:DocumentsTextfile.txt'>;> > >Console.WriteLine(>'Reading File using File.ReadAllText()'>);> > >// To read the entire file at once> >if> (File.Exists(file)) {> >// Read all the content in one string> >// and display the string> >string> str = File.ReadAllText(file);> >Console.WriteLine(str);> >}> >Console.WriteLine();> > >Console.WriteLine(>'Reading File using File.ReadAllLines()'>);> > >// To read a text file line by line> >if> (File.Exists(file)) {> >// Store each line in array of strings> >string>[] lines = File.ReadAllLines(file);> > >foreach>(>string> ln>in> lines)> >Console.WriteLine(ln);> >}> >Console.WriteLine();> > >Console.WriteLine(>'Reading File using StreamReader'>);> > >// By using StreamReader> >if> (File.Exists(file)) {> >// Reads file line by line> >StreamReader Textfile =>new> StreamReader(file);> >string> line;> > >while> ((line = Textfile.ReadLine()) !=>null>) {> >Console.WriteLine(line);> >}> > >Textfile.Close();> > >Console.ReadKey();> >}> >Console.WriteLine();> >}> }> |
bash for loop
>
>
Per executar aquest programa, deseu el fitxer amb .cs extensió i després es pot executar utilitzant csc nom de fitxer.cs comanda a cmd. O podeu utilitzar el Visual Studio. Aquí tenim un fitxer de text anomenat com Fitxer de text.txt que tenen el contingut mostrat a la sortida.
Sortida:

Escriure un fitxer de text: La classe File en C# defineix dos mètodes estàtics per escriure un fitxer de text, és a dir File.WriteAllText() i File.WriteAllLines() .
- El fitxer File.WriteAllText() escriu tot el fitxer alhora. Es necessita dos arguments, el camí del fitxer i el text que s'ha d'escriure.
- File.WriteAllLines() escriu un fitxer una línia a la vegada. Pren dos arguments, la ruta del fitxer i el text que s'ha d'escriure, que és una matriu de cadenes.
Hi ha una altra manera d'escriure en un fitxer i és mitjançant un objecte StreamWriter. El StreamWriter també escriu una línia a la vegada. Els tres mètodes d'escriptura creen un fitxer nou si el fitxer no existeix, però si el fitxer ja està present a la ubicació especificada, es sobreescriu. Totes les maneres esmentades anteriorment d'escriure en un fitxer de text s'il·lustren al codi d'exemple que es mostra a continuació.
// C# program to illustrate how> // to write a file in C#> using> System;> using> System.IO;> > class> Program {> >static> void> Main(>string>[] args)> >{> >// Store the path of the textfile in your system> >string> file =>@'M:DocumentsTextfile.txt'>;> > >// To write all of the text to the file> >string> text =>'This is some text.'>;> >File.WriteAllText(file, text);> > >// To display current contents of the file> >Console.WriteLine(File.ReadAllText(file));> >Console.WriteLine();> > >// To write text to file line by line> >string>[] textLines1 = {>'This is the first line'>,> >'This is the second line'>,> >'This is the third line'> };> > >File.WriteAllLines(file, textLines1);> > >// To display current contents of the file> >Console.WriteLine(File.ReadAllText(file));> > >// To write to a file using StreamWriter> >// Writes line by line> >string>[] textLines2 = {>'This is the new first line'>,> >'This is the new second line'> };> > >using>(StreamWriter writer =>new> StreamWriter(file))> >{> >foreach>(>string> ln>in> textLines2)> >{> >writer.WriteLine(ln);> >}> >}> >// To display current contents of the file> >Console.WriteLine(File.ReadAllText(file));> > >Console.ReadKey();> >}> }> |
>
>
Per executar aquest programa, deseu el fitxer amb .cs extensió i després es pot executar utilitzant csc nom de fitxer.cs comanda a cmd. O podeu utilitzar el Visual Studio.
Sortida:

xor c++
En cas que vulgueu afegir més text a un fitxer existent sense sobreescriure les dades ja emmagatzemades en ell, podeu utilitzar els mètodes d'afegir que ofereix la classe File de System.IO.
using> System;> using> System.IO;> > class> Program {> >static> void> Main(>string>[] args)> >{> >// Store the path of the textfile in your system> >string> file =>@'M:DocumentsTextfile.txt'>;> > >// To write all of the text to the file> >string> text1 =>'This is some text.'>;> >File.WriteAllText(file, text1);> > >// To append text to a file> >string> text2 =>'This is text to be appended'>;> >File.AppendAllText(file, text2);> > >// To display current contents of the file> >Console.WriteLine(File.ReadAllText(file));> >Console.ReadKey();> >}> }> |
>
>
Sortida:
