Was this page helpful?
Your feedback about this content is important. Let us know what you think.
Additional feedback?
1500 characters remaining
OpenWrite Method

FileInfo.OpenWrite Method

Creates a write-only FileStream.

Namespace:  System.IO
Assembly:  mscorlib (in mscorlib.dll)

public FileStream OpenWrite()

Return Value

Type: System.IO.FileStream
A write-only unshared FileStream object for a new or existing file.

ExceptionCondition
UnauthorizedAccessException

The path specified when creating an instance of the FileInfo object is read-only or is a directory.

DirectoryNotFoundException

The path specified when creating an instance of the FileInfo object is invalid, such as being on an unmapped drive.

The OpenWrite method opens a file if one already exists for the file path, or creates a new file if one does not exist. For an existing file, it does not append the new text to the existing text. Instead, it overwrites the existing characters with the new characters. If you overwrite a longer string (such as "This is a test of the OpenWrite method") with a shorter string (like "Second run"), the file will contain a mix of the strings ("Second runtest of the OpenWrite method").

The following example opens a file for writing and then reads from the file.

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

class Test 
{
    public static void Main() 
    {
        string path = @"c:\MyTest.txt";
        FileInfo fi = new FileInfo(path);

        // Open the stream for writing. 
        using (FileStream fs = fi.OpenWrite()) 
        {
            Byte[] info = 
                new UTF8Encoding(true).GetBytes("This is to test the OpenWrite method.");

            // Add some information to the file.
            fs.Write(info, 0, info.Length);
        }

        // Open the stream and read it back. 
        using (FileStream fs = fi.OpenRead()) 
        {
            byte[] b = new byte[1024];
            UTF8Encoding temp = new UTF8Encoding(true);

            while (fs.Read(b,0,b.Length) > 0) 
            {
                Console.WriteLine(temp.GetString(b));
            }
        }
    }
}
//This code produces output similar to the following;  
//results may vary based on the computer/file structure/etc.: 
// 
//This is to test the OpenWrite method. 
// 
// 
// 
// 
// 
// 
// 
// 
// 
// 
//

.NET Framework

Supported in: 4.6, 4.5, 4, 3.5, 3.0, 2.0, 1.1

.NET Framework Client Profile

Supported in: 4, 3.5 SP1

XNA Framework

Supported in: 3.0, 2.0, 1.0

.NET for Windows Phone apps

Supported in: Windows Phone 8.1, Windows Phone Silverlight 8.1, Windows Phone Silverlight 8
Show:
© 2015 Microsoft