Writing Files in C#

Here’s the translation of the Go code to C# with explanations in Markdown format suitable for Hugo:

Writing files in C# follows similar patterns to the ones we saw earlier for reading.

using System;
using System.IO;
using System.Text;

class WritingFiles
{
    static void Check(Exception e)
    {
        if (e != null)
        {
            throw e;
        }
    }

    static void Main()
    {
        // To start, here's how to dump a string (or just bytes) into a file.
        string content = "hello\nC#\n";
        try
        {
            File.WriteAllText("/tmp/dat1", content);
        }
        catch (Exception e)
        {
            Check(e);
        }

        // For more granular writes, open a file for writing.
        using (StreamWriter f = new StreamWriter("/tmp/dat2"))
        {
            // You can Write byte arrays as you'd expect.
            byte[] d2 = { 115, 111, 109, 101, 10 };
            int n2 = f.BaseStream.Write(d2, 0, d2.Length);
            Console.WriteLine($"wrote {n2} bytes");

            // A WriteString is also available.
            int n3 = f.Write("writes\n");
            Console.WriteLine($"wrote {n3} bytes");

            // Issue a Flush to ensure writes are written to stable storage.
            f.Flush();

            // StreamWriter provides buffered writers similar to bufio in Go.
            int n4 = f.Write("buffered\n");
            Console.WriteLine($"wrote {n4} bytes");

            // Use Flush to ensure all buffered operations have been applied to the underlying writer.
            f.Flush();
        }
    }
}

Try running the file-writing code.

$ dotnet run
wrote 5 bytes
wrote 7 bytes
wrote 9 bytes

Then check the contents of the written files.

$ cat /tmp/dat1
hello
C#
$ cat /tmp/dat2
some
writes
buffered

Next we’ll look at applying some of the file I/O ideas we’ve just seen to the Console.In and Console.Out streams.