C# File OpenWrite

Description

File OpenWrite Opens an existing file or creates a new file for writing.

Syntax

File.OpenWrite has the following syntax.


public static FileStream OpenWrite(
  string path
)

Parameters

File.OpenWrite has the following parameters.

  • path - The file to be opened for writing.

Returns

File.OpenWrite method returns An unshared FileStream object on the specified path with Write access.

Example

The following example opens a file for reading and writing.


//from  w  w  w  .j ava  2  s  . co m
using System;
using System.IO;
using System.Text;

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

        using (FileStream fs = File.OpenWrite(path)) 
        {
            Byte[] info = new UTF8Encoding(true).GetBytes("This is to test the OpenWrite method.");

            fs.Write(info, 0, info.Length);
        }

        using (FileStream fs = File.OpenRead(path)) 
        {
            byte[] b = new byte[1024];
            UTF8Encoding temp = new UTF8Encoding(true);

            while (fs.Read(b,0,b.Length) > 0) 
            {
                Console.WriteLine(temp.GetString(b));
            }
        }
    }
}




















Home »
  C# Tutorial »
    System.IO »




BinaryReader
BinaryWriter
Directory
DirectoryInfo
DriveInfo
File
FileInfo
FileStream
MemoryStream
Path
StreamReader
StreamWriter
StringReader
StringWriter