C# File OpenWrite() Method

Beginner
5 min read
Updated: Nov 2026
3 examples
System.IO

Definition

In C#, File.OpenWrite() opens a file for writing only and returns a FileStream. If the file does not exist, it is created. If it exists, it is opened without being emptied.

The stream starts at position zero, so new bytes replace the old ones from the start. If your new data is shorter than the old content, the extra old bytes stay behind. This surprises many beginners.

This is a static method of System.IO.File. Call it as File.OpenWrite(...); there is no new File(). For an object that remembers one file, see FileInfo.

Syntax

Write into the stream, and call SetLength when the new content may be shorter than the old content.

C#
string path = Path.Combine(Path.GetTempPath(), "codetofun-openwrite.bin");

using (FileStream fs = File.OpenWrite(path)) {
    fs.WriteByte(65);
    fs.SetLength(fs.Position);
}
CallWhat it does
File.OpenWrite(path)Creates the file if needed, or opens it as it is. Position starts at zero.
fs.SetLength(fs.Position)Cuts off anything after the current position. Use it to remove leftover bytes.
fs.Seek(0, SeekOrigin.End)Moves to the end, so writing adds to the file instead of replacing the start.

OpenWrite equals File.Open(path, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None). File.Create is different: it always empties the file.

Library declarations
C#
public static FileStream OpenWrite(string path);

Parameters

ParameterDescription
pathThe file to open or create for writing. Its folder must exist.

Return Value

Return ValueDescription
FileStreamA write-only stream at position zero. Reading from it throws NotSupportedException.

C# Examples

Example 1 — Open a New File for Writing

Use OpenWrite on a path that does not exist yet and write a few bytes.

C#
using System;
using System.IO;
using System.Text;

class Program {
    static void Main() {
        string root = Path.Combine(Path.GetTempPath(), "codetofun-file-openwrite");
        if (Directory.Exists(root)) Directory.Delete(root, true);
        Directory.CreateDirectory(root);

        string path = Path.Combine(root, "hello.txt");
        Console.WriteLine(File.Exists(path));

        using (FileStream fs = File.OpenWrite(path)) {
            byte[] data = Encoding.UTF8.GetBytes("Hello");
            fs.Write(data, 0, data.Length);
        }

        Console.WriteLine(File.Exists(path));
        Console.WriteLine(File.ReadAllText(path));

        Directory.Delete(root, true);
    }
}

How It Works

  1. Not there yet. The first Exists prints False, so OpenWrite has nothing to open.
  2. It creates the file. Unlike OpenRead, the call does not fail. It makes an empty file and returns the stream.
  3. Encode, write, close. GetBytes turns the text into bytes, Write saves them, and the using block closes the file. Reading it back gives Hello.

Example 2 — The Leftover Bytes Gotcha and Its Fix

Write a short text over a longer file, see the leftovers, and then remove them with SetLength.

C#
using System;
using System.IO;
using System.Text;

class Program {
    static void Main() {
        string root = Path.Combine(Path.GetTempPath(), "codetofun-file-openwrite-gotcha");
        if (Directory.Exists(root)) Directory.Delete(root, true);
        Directory.CreateDirectory(root);

        string path = Path.Combine(root, "letters.txt");
        File.WriteAllText(path, "ABCDEFGHIJ");

        byte[] shortText = Encoding.UTF8.GetBytes("xyz");

        using (FileStream fs = File.OpenWrite(path)) {
            fs.Write(shortText, 0, shortText.Length);
        }
        Console.WriteLine(File.ReadAllText(path));

        using (FileStream fs = File.OpenWrite(path)) {
            fs.Write(shortText, 0, shortText.Length);
            fs.SetLength(fs.Position);
        }
        Console.WriteLine(File.ReadAllText(path));

        Directory.Delete(root, true);
    }
}

How It Works

  1. Start with ten letters. The file holds ABCDEFGHIJ. OpenWrite keeps those bytes and puts the position at zero.
  2. Three bytes overwrite three bytes. Writing xyz replaces ABC, but DEFGHIJ is untouched, so the file reads xyzDEFGHIJ.
  3. Cut the tail. After the write, fs.Position is 3. SetLength(3) drops everything after it.
  4. Cleaner result. The second read prints only xyz. File.Create would have avoided the problem by emptying the file first.

Example 3 — Seek to the End and Add More

Move the position to the end before writing so existing content is kept.

C#
using System;
using System.IO;
using System.Text;

class Program {
    static void Main() {
        string root = Path.Combine(Path.GetTempPath(), "codetofun-file-openwrite-seek");
        if (Directory.Exists(root)) Directory.Delete(root, true);
        Directory.CreateDirectory(root);

        string path = Path.Combine(root, "story.txt");
        File.WriteAllText(path, "start");

        using (FileStream fs = File.OpenWrite(path)) {
            fs.Seek(0, SeekOrigin.End);
            byte[] more = Encoding.UTF8.GetBytes("-end");
            fs.Write(more, 0, more.Length);
            Console.WriteLine(fs.Position);
        }

        Console.WriteLine(File.ReadAllText(path));

        Directory.Delete(root, true);
    }
}

How It Works

  1. Position matters. A stream from OpenWrite begins at zero, so a plain write would overwrite start.
  2. Jump to the end. Seek(0, SeekOrigin.End) moves the position to byte 5, just after the last letter.
  3. Write and measure. Four bytes of -end are added, so the position becomes 9, which is also the new file size.
  4. Result. The file reads start-end. For this job File.AppendAllText is simpler, but Seek gives control over any position.

Frequently Asked Questions

No. It opens the file without truncating it, so old bytes beyond what you write remain. Use File.Create to empty the file, or call SetLength after writing.
Yes. If the path does not exist, an empty file is created. The folder, however, must already exist.
Both give a writable FileStream and create missing files. Create empties an existing file and allows reading too, while OpenWrite keeps old content and allows writing only.
Call fs.Seek(0, SeekOrigin.End) before writing, or open with File.Open(path, FileMode.Append, FileAccess.Write). File.AppendAllText is the shortest choice for text.
The stream uses FileShare.None until it is disposed. Wrap it in a using block so the lock is released at the closing brace.

Next: ReadAllBytes()

Read the raw bytes of a whole file into a byte array.

ReadAllBytes() tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

10 people found this page helpful