System.IO.FileInfo.OpenRead 方法

方法描述

创建只读 FileStream。

语法定义(C# System.IO.FileInfo.OpenRead 方法 的用法)

public FileStream OpenRead()

参数/返回值

参数值/返回值 参数类型/返回类型 参数描述/返回描述
返回值 System.IO.FileStream 新的只读 FileStream 对象。

提示和注释

该方法返回一个 FileShare 模式设置为 Read 的只读 FileStream 对象。

System.IO.FileInfo.OpenRead 方法例子

下面的示例以只读方式打开一个文件并从中读取。

using System;
using System.IO;
using System.Text;

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

        // Delete the file if it exists.
        if (!fi.Exists) 
        {
            //Create the file.
            using (FileStream fs = fi.Create()) 
            {
                Byte[] info = new UTF8Encoding(true).GetBytes("This is some text in the file.");
                //Add some information to the file.
                fs.Write(info, 0, info.Length);
            }
        }

        //Open the stream and read it back.
        using (FileStream fs = fi.OpenRead()) 
        {
            byte[] b = new byte[1024];
            UTF8Encoding temp = new UTF8Encoding(true);

            while (fs.Read(b,0,b.Length) > 0) 
            {
                Console.WriteLine(temp.GetString(b));
            }
        }
    }
}
//This code produces output similar to the following; 
//results may vary based on the computer/file structure/etc.:
//
//This is some text in the file.
//
//
//
//
//
//
//
//
//
//
//
//

异常

异常 异常描述
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 系统要求。