How to use File.OpenWrite in C#

By FoxLearn 6/11/2024 1:49:29 AM   349
In C#, the File.OpenWrite method is used to open an existing file or create a new file for writing.

It returns a FileStream object that can be used to write to the file. Here's a step-by-step guide on how to use File.OpenWrite in c#.

You can use the FileStream.Write method to write bytes to the file.

string fileName = "c://fileName.txt";
using (FileStream fs = File.OpenWrite(fileName))
{
    byte[] data = new System.Text.UTF8Encoding(true).GetBytes("C# Programming");
    fs.Write(data, 0, data.Length);
}

Or you can also use StreamWriter

string fileName = "C://fileName.txt";
using (FileStream fs = File.OpenWrite(fileName))
{
    using (StreamWriter writer = new StreamWriter(fs))
    {
        writer.WriteLine("C# Programming");
    }
}

Here's a simpe example that demonstrates opening a file for writing, writing some text data, and closing the file properly.

using System;
using System.IO;

class Program
{
    static void Main()
    {
        string fileName = "C://example.txt";
        // c# open the file for writing. If the file doesn't exist, it will be created.
        using (FileStream fs = File.OpenWrite(fileName))
        {
            // c# write a string to the file
            using (StreamWriter writer = new StreamWriter(fs))
            {
                writer.WriteLine("Welcome to FoxLearn");
                writer.WriteLine("This is an example of using File.OpenWrite in C#.");
            }
        }
    }
}

If the file specified in the path does not exist, File.OpenWrite will create a new file.

If the file already exists, File.OpenWrite will overwrite the existing content starting from the beginning of the file. It does not truncate the file, so any remaining content beyond the new content will stay intact.

Or you can also combine it with the FileInfo class

string fileName = @"C:/fileName.txt";
FileInfo fi = new FileInfo(fileName);
// If file does not exist, create file
if (!fi.Exists)
{
   // c# create the file.
   using (FileStream fs = fi.Create())
   {
      Byte[] info = new UTF8Encoding(true).GetBytes("Welcome to FoxLearn !");
      fs.Write(info, 0, info.Length);
   }
}
try
{
   // c# open a file and add some contents to it
   using (FileStream fs = fi.OpenWrite())
   {
      Byte[] data = new UTF8Encoding(true).GetBytes("This is an example of using File.OpenWrite in C#.");
      fs.Write(data, 0, data.Length);      
   }
   // c# read file contents and display on the console
   using (FileStream fs = File.OpenRead(fileName))
   {
      byte[] byteArray = new byte[1024];
      UTF8Encoding utf8 = new UTF8Encoding(true);
      while (fs.Read(byteArray, 0, byteArray.Length) > 0)
      {
         Console.WriteLine(utf8.GetString(byteArray));
      }
   }
}
catch (Exception ex)
{
   Console.WriteLine(ex.Message);
}

Note, the file must be opened using an IO resource before it can be read or write to.