C# File Open(String, FileMode, FileAccess, FileShare)

Description

File Open(String, FileMode, FileAccess, FileShare) Opens a FileStream on the specified path, having the specified mode with read, write, or read/write access and the specified sharing option.

Syntax

File.Open(String, FileMode, FileAccess, FileShare) has the following syntax.


public static FileStream Open(
  string path,//from  w w  w  . j  a  v a2 s.c o m
  FileMode mode,
  FileAccess access,
  FileShare share
)

Parameters

File.Open(String, FileMode, FileAccess, FileShare) has the following parameters.

  • path - The file to open.
  • mode - A FileMode value that specifies whether a file is created if one does not exist, and determines whether the contents of existing files are retained or overwritten.
  • access - A FileAccess value that specifies the operations that can be performed on the file.
  • share - A FileShare value specifying the type of access other threads have to the file.

Returns

File.Open(String, FileMode, FileAccess, FileShare) method returns A FileStream on the specified path, having the specified mode with read, write, or read/write access and the specified sharing option.

Example

The following example opens a file with read-only access and with file sharing disallowed.


//w  w  w  .ja va 2s . com
using System;
using System.IO;
using System.Text;

class Test 
{
    public static void Main() 
    {
        string path = "MyTest.txt";
        if (!File.Exists(path)) 
        {
            using (FileStream fs = File.Create(path)) 
            {
                Byte[] info = new UTF8Encoding(true).GetBytes("from java2s.com.");
                fs.Write(info, 0, info.Length);
            }
        }
        using (FileStream fs = File.Open(path, FileMode.Open, FileAccess.Read, FileShare.None)) 
        {
            byte[] b = new byte[1024];
            UTF8Encoding temp = new UTF8Encoding(true);
            while (fs.Read(b,0,b.Length) > 0) 
            {
                Console.WriteLine(temp.GetString(b));
            }

            try 
            {
                using (FileStream fs2 = File.Open(path, FileMode.Open)) 
                {
                }
            } 
            catch (Exception e) 
            {
                Console.Write("Opening the file twice is disallowed.");
                Console.WriteLine(", as expected: {0}", e.ToString());
            }
        }
    }
}




















Home »
  C# Tutorial »
    System.IO »




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