Export (0) Print
Expand All

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.5.2, 4.5.1, 4.5, 4, 3.5, 3.0, 2.0, 1.1, 1.0

.NET Framework Client Profile

Supported in: 4, 3.5 SP1

.NET for Windows Phone apps

Supported in: Windows Phone 8.1, Windows Phone 8, Silverlight 8.1

Windows Phone 8.1, Windows Phone 8, Windows 8.1, Windows Server 2012 R2, Windows 8, Windows Server 2012, Windows 7, Windows Vista SP2, Windows Server 2008 (Server Core Role not supported), Windows Server 2008 R2 (Server Core Role supported with SP1 or later; Itanium not supported)

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

Show:
© 2014 Microsoft