create a text file and print a value in it in csharp

To create a text file and print a value in it, we can use the StreamWriter class in C#. Here's an example:

main.cs
using System;
using System.IO;

class Program
{
    static void Main(string[] args)
    {
        string fileName = "output.txt";
        int value = 42;

        using(StreamWriter writer = new StreamWriter(fileName))
        {
            writer.WriteLine(value);
        }

        Console.WriteLine("Value {0} printed to file \"{1}\".", value, fileName);
    }
}
367 chars
19 lines

In the example above, we first define the name of the file we want to create (output.txt) and the value we want to print to it (42).

We then create a new StreamWriter object and pass the file name as an argument to the constructor (new StreamWriter(fileName)). We then call the WriteLine method of the StreamWriter object and pass the value we want to print (value) as an argument. This writes the value to the text file.

Finally, we print a message to the console to confirm that the value was printed to the file.

Note that we are using a using block with the StreamWriter object. This ensures that the StreamWriter is disposed of properly when we are done using it.

gistlibby LogSnag