System.IO.FileInfo.Open 方法 (FileMode, FileAccess, FileShare)

方法描述

用读、写或读/写访问权限和指定的共享选项在指定的模式中打开文件。

语法定义(C# System.IO.FileInfo.Open 方法 (FileMode, FileAccess, FileShare) 的用法)

public FileStream Open(
	FileMode mode,
	FileAccess access,
	FileShare share
)

参数/返回值

参数值/返回值 参数类型/返回类型 参数描述/返回描述
mode System-IO-FileMode 一个 FileMode 常数,它指定打开文件所采用的模式(例如 Open 或 Append)。
access System-IO-FileAccess 一个 FileAccess 常数,它指定是使用 Read、Write 还是 ReadWrite 文件访问权限来打开文件。
share System-IO-FileShare 一个 FileShare 常数,它指定其他 FileStream 对象对此文件拥有的访问类型。
返回值 System.IO.FileStream 用指定的模式、访问权限和共享选项打开的 FileStream 对象。

提示和注释

System.IO.FileInfo.Open 方法 (FileMode, FileAccess, FileShare)例子

下面的示例演示了如何打开一个文件进行读取和写入操作,但不允许其他用户或进程访问。

using System;
using System.IO;

public class OpenTest 
{
    public static void Main() 
    {
        // Open an existing file, or create a new one.
        FileInfo fi = new FileInfo("temp.txt");

        // Open the file just specified such that no one else can use it.
        FileStream fs = fi.Open( FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None );

        // Create another reference to the same file.
        FileInfo nextfi = new FileInfo("temp.txt");        

        try 
        {
            // Try opening the same file, which was locked by the previous process.
            nextfi.Open( FileMode.OpenOrCreate, FileAccess.Read );

            Console.WriteLine("The file was not locked, and was opened by a second process.");
        } 
        catch (IOException) 
        {
            Console.WriteLine("The file could not be opened because it was locked by another process.");
        } 
        catch (Exception e) 
        {
            Console.WriteLine(e.ToString());
        }

        // Close the file so it can be deleted.
        fs.Close();
    }
}

//This code produces output similar to the following; 
//results may vary based on the computer/file structure/etc.:
//
//The file could not be opened because it was locked by another process.

异常

异常 异常描述
SecurityException 调用方没有所要求的权限。
ArgumentException path 为空,或者只包含空白。
FileNotFoundException 找不到该文件。
ArgumentNullException 一个或多个参数为 null。
UnauthorizedAccessException path 为只读,或者是一个目录。
DirectoryNotFoundException 指定的路径无效,比如在未映射的驱动器上。
IOException 该文件已打开。

命名空间

namespace: System.IO

程序集: mscorlib(在 mscorlib.dll 中)

版本信息

.NET Framework 受以下版本支持:4、3.5、3.0、2.0、1.1、1.0 .NET Framework Client Profile 受以下版本支持:4、3.5 SP1

适用平台

Windows 7, Windows Vista SP1 或更高版本, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008(不支持服务器核心), Windows Server 2008 R2(支持 SP1 或更高版本的服务器核心), Windows Server 2003 SP2 .NET Framework 并不是对每个平台的所有版本都提供支持。有关支持的版本的列表,请参见.NET Framework 系统要求。