Pliki w C#

Info o plikach w C#: https://learn.microsoft.com/en-us/dotnet/standard/io/how-to-write-text-to-a-file

Zapisywanie do pliku

Tworzenie pliku tekstowego i zapis informacji

string fileName = "myfile.txt";
string path = "myfile.txt";
string path = Path.Combine(@"", fileName);
//string path = Path.Combine(@"E:/", fileName);
//string path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), fileName); 
//string path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), fileName); 


//using StreamWriter sw = File.CreateText(path);

using (StreamWriter sw = new(path))
{
    sw.WriteLine(DateTime.Now);
    sw.Close();
}

// dodaj argument true, aby dołączać (append) informacje do pliku
string path = @"myfilex.txt";

using (StreamWriter sw = new(path, true))
{
    sw.WriteLine(DateTime.Now);
    sw.Close();
}



Zapis informacji do pliku asynchronicznie


WriteCharacters(DateTime.Now.ToString());

static async void WriteCharacters(string msg)
{
    string path = @"myfile.txt";
    using (StreamWriter sw = new(path, true))
    {
        //await sw.WriteAsync(msg);
        await sw.WriteLineAsync(msg);
        sw.Close();
    }
}

Zapis elementów tablicy do pliku txt

string[] lines = { "First line", "Second line", "Third line" };

string docPath = @"myfile.txt" ;
using (StreamWriter outputFile = new(docPath))
{
    foreach (string line in lines)
        outputFile.WriteLine(line);
}

Odczytywanie z pliku

Proste odczytywanie danych z pliku

string path = @"myfile.txt";
string contents = File.ReadAllText(path);
Console.WriteLine(contents);

//lub

using System.Text;
string path = @"myfile.txt";

string contents;
using (StreamReader streamReader = new StreamReader(path, Encoding.UTF8))
{
    contents = streamReader.ReadToEnd();
}

Console.WriteLi  bne(contents);

Odczytywanie danych z pliku linia po linii

// Read a text file line by line.

string path = @"myfile.txt";
if (File.Exists(path))
{
    string[] lines = File.ReadAllLines(path);

    foreach (string line in lines)
    {
        Console.WriteLine(line);
    }
}


// Read a text file line by line with StreamReader

string path = @"myfile.txt";
if (File.Exists(path))
{
    using (StreamReader sr = File.OpenText(path))
    {
        string s;
        while ((s = sr.ReadLine()) != null)
        {
            Console.WriteLine(s);
        }
        sr.Close();
    }
}

Pobierz linie z pliku i zapisz je do listy

string fileName = "myfile.txt";
string path = Path.Combine(@"", fileName);

List<string> lines = new();

if (File.Exists(path))
{
    using StreamReader sr = new(path);
    string s;
    while ((s = sr.ReadLine()) != null)
    {
        lines.Add(s);
    }

    sr.Close();

    foreach (string line in lines)
    {
        Console.WriteLine(line);
    }
}

Scroll to Top