C# FileInfo Open(FileMode, FileAccess, FileShare)

Description

FileInfo Open(FileMode, FileAccess, FileShare) Opens a file in the specified mode with read, write, or read/write access and the specified sharing option.

Syntax

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


public FileStream Open(
  FileMode mode,/*from  w ww  .  ja  va2s .c  o  m*/
  FileAccess access,
  FileShare share
)

Parameters

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

  • mode - A FileMode constant specifying the mode (for example, Open or Append) in which to open the file.
  • access - A FileAccess constant specifying whether to open the file with Read, Write, or ReadWrite file access.
  • share - A FileShare constant specifying the type of access other FileStream objects have to this file.

Returns

FileInfo.Open(FileMode, FileAccess, FileShare) method returns A FileStream object opened with the specified mode, access, and sharing options.

Example

The following example demonstrates opening a file for reading and writing, but disallowing access to other users or processes.


/*from  w  w w .  j a  va  2s .c  om*/
using System;
using System.IO;

public class OpenTest 
{
    public static void Main() 
    {
        FileInfo fi = new FileInfo("temp.txt");
        FileStream fs = fi.Open( FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None );
        FileInfo nextfi = new FileInfo("temp.txt");        
        try 
        {
            nextfi.Open( FileMode.OpenOrCreate, FileAccess.Read );
        } 
        catch (IOException) 
        {
            Console.WriteLine("The file could not be opened because it was locked by another process.");
        } 
        catch (Exception e) 
        {
            Console.WriteLine(e.ToString());
        }
        fs.Close();
    }
}

The code above generates the following result.





















Home »
  C# Tutorial »
    System.IO »




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