logo

Hur man läser och skriver en textfil i C#?

Uppsägning av ett program leder till radering av all data relaterade till det. Därför måste vi lagra data någonstans. Filer används för att permanent lagra och dela data. C# kan användas för att hämta och manipulera data lagrade i textfiler.

bash sträng längd

Läsa en textfil: Filklassen i C# definierar två statiska metoder för att läsa en textfil, nämligen File.ReadAllText() och File.ReadAllLines() .



  • File.ReadAllText() läser hela filen på en gång och returnerar en sträng. Vi måste lagra denna sträng i en variabel och använda den för att visa innehållet på skärmen.
  • File.ReadAllLines() läser en fil en rad i taget och returnerar den raden i strängformat. Vi behöver en rad strängar för att lagra varje rad. Vi visar innehållet i filen med samma strängarray.

Det finns ett annat sätt att läsa en fil och det är genom att använda ett StreamReader-objekt. StreamReader läser också en rad i taget och returnerar en sträng. Alla de ovan nämnda sätten att läsa en fil illustreras i exempelkoden nedan.








// 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();> >}> }>

>

matte pow java

>

För att köra detta program, spara filen med .cs förlängning och sedan kan köras med csc filnamn.cs kommando på cmd. Eller så kan du använda Visual Studio . Här har vi en textfil som heter som Textfile.txt som har innehållet som visas i utdata.

Produktion:

läsa textfil i C#

Skriva en textfil: Filklassen i C# definierar två statiska metoder för att skriva en textfil, nämligen File.WriteAllText() och File.WriteAllLines() .

  • File.WriteAllText() skriver hela filen på en gång. Det krävs två argument, sökvägen till filen och texten som ska skrivas.
  • File.WriteAllLines() skriver en fil en rad i taget. Det krävs två argument, sökvägen till filen och texten som måste skrivas, vilket är en strängmatris.

Det finns ett annat sätt att skriva till en fil och det är genom att använda ett StreamWriter-objekt. StreamWriter skriver också en rad i taget. Alla de tre skrivmetoderna skapar en ny fil om filen inte finns, men om filen redan finns på den angivna platsen skrivs den över. Alla de ovan nämnda sätten att skriva till en textfil illustreras i exempelkoden nedan.


java char till int



// 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();> >}> }>

>

objekt för java
>

För att köra detta program, spara filen med .cs förlängning och sedan kan köras med csc filnamn.cs kommando på cmd. Eller så kan du använda Visual Studio .

Produktion:

skriva en fil i C#

Om du vill lägga till mer text till en befintlig fil utan att skriva över de data som redan finns lagrade i den, kan du använda de tilläggsmetoder som tillhandahålls av klassen File i System.IO.


np prick



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();> >}> }>

>

>

Produktion:

lägga till text i en fil i C#