Zapis i odczyt z pliku w C#

Potrzebne elementy są w przestrzeni nazw System.IO

using System.IO;

Użyteczne metody klasy File

bool File.Exists(string path) - metoda statyczna, sprawdzenie, czy plik istnieje:

 
	if (File.Exists(@"C:\kat\plik.txt"))
	{
		//...
	}

void File.WriteAllText(string path, string content) - metoda statyczna, zapis łańcucha znaków content do pliku tekstowego:

      string s = "Tekst\r\n\do zapisu\r\nw pliku!";
      File.WriteAllText(@"d:\x.txt", s);

void File.WriteAllLines(string path, string[] tab) - metoda statyczna, zapis tablicy łańcuchów znaków tab do pliku tekstowego:

      string[] t = new string[3];
      t[0] = "Inny tekst";
      t[1] = "do zapisu";
      t[2] = "w pliku!";
      File.WriteAllLines(@"d:\x.txt", t);

string File.ReadAllText(string path) - metoda statyczna, zwraca całą zawartość pliku tekstowego w łańcuchu znaków:

      string s = File.ReadAllText(@"d:\x.txt");

string[] File.ReadAllLines(string path) - metoda statyczna, zwraca wszystkie linie pliku tekstowego w tablicy łańcuchów znaków:

      string[] t = File.ReadAllLines(@"d:\x.txt");

Użycie klasy FileStream

Odczyt zawartości pliku jako tablicy bajtów:

      byte[] data;
      string path = @"d:\x.txt";
      if (File.Exists(path))
      {
        FileStream fs = new System.IO.FileStream(path, FileMode.Open);
        data = new byte[fs.Length];
        fs.Position = 0;
        fs.Read(data, 0, (int)fs.Length);
        fs.Close();
      }

Zapis tablicy bajtów jako zawartości pliku:

      string s = "Ala ma kota\r\nA kot ma Alę!";
      byte[] data = Encoding.UTF8.GetBytes(s);
      string path = @"d:\x.txt";
      FileStream fs = new System.IO.FileStream(path, FileMode.Create);
      fs.Write(data, 0, data.Length);
      fs.Close();

Użycie klas StreamWriter i StreamReader

Zapis "po kawałku" do pliku:

      string path = @"d:\x.txt";
      StreamWriter sw = new StreamWriter(path);
      sw.Write("Ala");
      sw.WriteLine(" ma kota");
      sw.WriteLine("i tak dalej!");
      sw.Close();

Odczyt "po kawałku" z pliku:

      StringBuilder sb = new StringBuilder();
      string path = @"d:\x.txt";
      StreamReader sr = new StreamReader(path);
      string s;
      do
      {
        s = sr.ReadLine();
        sb.AppendLine(s);
      } while (s != null);
      sr.Close();