C#C
C#9mo ago
Faker

✅ StreamWriter not writing to file

Hello guys, I changed my file properties to "Copy if newer" (I didn't understand why we need to do that, would really appreciate if someone can explain) .... I was able to read a file but when it comes to write to it, it seems that nothing is being written and no exception is being thrown (I added the .close method).

C#
// How to read and write to file in C#
string filePath = Path.GetFullPath("sample.txt");

try
{
    var sr = new StreamReader(filePath);
    var line = sr.ReadLine();
    Console.WriteLine(line);
    sr.Close();
}
catch (Exception e)
{
    Console.WriteLine(e.Message);
}

try
{
    using (var sw = new StreamWriter(filePath, true, Encoding.Unicode))
    {
        sw.WriteLine("Just a new line");
        sw.WriteLine("Just a new line 2");
    }
    
}
catch (Exception e)
{
    Console.WriteLine($"Processing failed: {e.Message}");
}
finally
{
    Console.WriteLine("Finally block executed");
}
Was this page helpful?