© 2026 Hedgehog Software, LLC

TwitterGitHubDiscord
More
CommunitiesDocsAboutTermsPrivacy
Search
Star
Setup for Free
C#C
C#•11mo ago•
63 replies
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).

// 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");
}
// 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");
}
C# banner
C#Join
We are a programming server aimed at coders discussing everything related to C# (CSharp) and .NET.
61,871Members
Resources

Similar Threads

Was this page helpful?
Recent Announcements
Next page

Similar Threads

✅ StreamWriter not writing to file
C#CC# / help
2y ago
❔ Writing to StreamWriter Fails
C#CC# / help
3y ago
Write to file not working (StreamWriter)
C#CC# / help
4y ago
StreamWriter writing some lines multiple times
C#CC# / help
2y ago