C# File Open(String, FileMode, FileAccess)

Description

File Open(String, FileMode, FileAccess) Opens a FileStream on the specified path, with the specified mode and access.

Syntax

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


public static FileStream Open(
  string path,/*  w w  w.  ja va 2 s. co  m*/
  FileMode mode,
  FileAccess access
)

Parameters

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

Returns

File.Open(String, FileMode, FileAccess) method returns An unshared FileStream that provides access to the specified file, with the specified mode and access.

Example

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


/*  w w w  .  j a v a2s . c om*/
using System;
using System.IO;
using System.Text;

class Test 
{
    public static void Main() 
    {
        string filePath = @"c:\temp\MyTest.txt";
        using (FileStream fs = File.Create(filePath)) 
        {
            Byte[] info = new UTF8Encoding(true).GetBytes("from java2s.com.");
            fs.Write(info, 0, info.Length);
        }
        using (FileStream fs = File.Open(filePath, 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 
            {
                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