Write to a File With OpenWrite Using C#

The OpenWrite method opens a file for writing. If the file does not exist, it creates a new file and opens it for writing. The OpenWrite method takes a file name as parameter and returns a FileStream object on the specified file.

FileStream fs = File.OpenWrite(fileName);

With the FileStream object we can use its Write method to write to the file. The WriteMethod takes a byte array. The following code snippet creates a byte array and passes it to the Write method of the FileStream:

Byte[] info = new UTF8Encoding(true).GetBytes("New File using OpenWrite Method \n");
fs.Write(info, 0, info.Length);

The following shows the complete code of the sample:

string fileName = @"C:\Temp\FOWM.txt";
try

{
   
// Open a file and add some contents to it
    using (FileStream fs = File.OpenWrite(fileName))
    {
        Byte[] info = new UTF8Encoding(true).GetBytes("New File using OpenWrite Method \n");
        fs.Write(info, 0, info.Length);
        info = new UTF8Encoding(true).GetBytes("----------START------------------------ \n");
        fs.Write(info, 0, info.Length);
        info = new UTF8Encoding(true).GetBytes("Author: Mahesh Chand \n");
        fs.Write(info, 0, info.Length);
        info = new UTF8Encoding(true).GetBytes("Book: ADO.NET Programming using C# \n");
        fs.Write(info, 0, info.Length);
        info = new UTF8Encoding(true).GetBytes("----------END------------------------");
        fs.Write(info, 0, info.Length);
    }
   
// Read file contents and display on the console
    using (FileStream fs = File.OpenRead(fileName))
    {
        byte[] byteArray = new byte[1024];
        UTF8Encoding fileContent = new UTF8Encoding(true);
        while (fs.Read(byteArray, 0, byteArray.Length) > 0)
        {
            Console.WriteLine(fileContent.GetString(byteArray));
        }
    }
}

catch
(Exception Ex)
{
    Console.WriteLine(Ex.ToString());
}

Up Next
    Ebook Download
    View all
    Learn
    View all