C# FileInfo Open(FileMode, FileAccess)

Description

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

Syntax

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


public FileStream Open(
  FileMode mode,
  FileAccess access
)

Parameters

FileInfo.Open(FileMode, FileAccess) 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.

Returns

FileInfo.Open(FileMode, FileAccess) method returns A FileStream object opened in the specified mode and access, and unshared.

Example

The following example opens a file as read-only and reads from the file.


//from  www  .ja  v  a  2 s.  co  m
using System;
using System.IO;
using System.Text;

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

        using (FileStream fs = fi.Open(FileMode.Open, FileAccess.Read)) 
        {
            byte[] b = new byte[1024];
            UTF8Encoding temp = new UTF8Encoding(true);
            while (fs.Read(b,0,b.Length) > 0) 
            {
                Console.WriteLine(temp.GetString(b));
            }

            try 
            {
                //Try to write to the file.
                fs.Write(b,0,b.Length);
            } 
            catch (Exception e) 
            {
                Console.WriteLine("Writing was disallowed, as expected: {0}",
                    e.ToString());
            }
        }
    }
}




















Home »
  C# Tutorial »
    System.IO »




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