Jak czytać i pisać plik tekstowy w C#?
Zakończenie programu powoduje usunięcie wszystkich danych z nim związanych. Dlatego musimy gdzieś przechowywać dane. Pliki służą do trwałego przechowywania i udostępniania danych. C# można używać do pobierania i manipulowania danymi przechowywanymi w plikach tekstowych.
Czytanie pliku tekstowego: Klasa pliku w języku C# definiuje dwie statyczne metody odczytu pliku tekstowego, a mianowicie Plik.ReadAllText() I Plik.ReadAllLines() .
- Funkcja File.ReadAllText() odczytuje cały plik na raz i zwraca ciąg znaków. Musimy zapisać ten ciąg w zmiennej i użyć go do wyświetlenia zawartości na ekranie.
- Funkcja File.ReadAllLines() odczytuje plik po wierszu na raz i zwraca ten wiersz w formacie ciągu. Potrzebujemy tablicy ciągów do przechowywania każdej linii. Wyświetlamy zawartość pliku przy użyciu tej samej tablicy ciągów.
Istnieje inny sposób odczytania pliku, a mianowicie użycie obiektu StreamReader. StreamReader również odczytuje jedną linię na raz i zwraca ciąg. Wszystkie powyższe sposoby odczytu pliku zilustrowano w przykładowym kodzie podanym poniżej.
// 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();> > }> }> |
Aby uruchomić ten program, zapisz plik za pomocą .cs rozszerzenie, a następnie można wykonać za pomocą csc nazwa pliku.cs polecenie na cmd. Możesz też użyć Visual Studio. Tutaj mamy plik tekstowy o nazwie jako Plik tekstowy.txt których zawartość jest pokazana na wyjściu.
Wyjście:
Zapisywanie pliku tekstowego: Klasa File w języku C# definiuje dwie statyczne metody zapisu pliku tekstowego, a mianowicie Plik.WriteAllText() I Plik.WriteAllLines() .
- Funkcja File.WriteAllText() zapisuje cały plik na raz. Pobiera dwa argumenty, ścieżkę pliku i tekst, który ma zostać zapisany.
- Funkcja File.WriteAllLines() zapisuje plik po jednym wierszu na raz. Pobiera dwa argumenty, ścieżkę pliku i tekst, który ma zostać zapisany, czyli tablicę ciągów.
Istnieje inny sposób zapisu do pliku, a mianowicie użycie obiektu StreamWriter. StreamWriter zapisuje również jedną linię na raz. Wszystkie trzy metody zapisu tworzą nowy plik, jeśli plik nie istnieje, ale jeśli plik znajduje się już w określonej lokalizacji, zostaje nadpisany. Wszystkie powyższe sposoby zapisu do pliku tekstowego zilustrowano w przykładowym kodzie podanym poniżej.
// 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();> > }> }> |
Aby uruchomić ten program, zapisz plik za pomocą .cs rozszerzenie, a następnie można wykonać za pomocą csc nazwa pliku.cs polecenie na cmd. Możesz też użyć Visual Studio.
Wyjście:
Jeśli chcesz dodać więcej tekstu do istniejącego pliku bez nadpisywania danych już w nim przechowywanych, możesz skorzystać z metod dołączania dostarczonych przez klasę File 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();> > }> }> |
Wyjście: