FileStream.CanRead 屬性

定義

取得值,表示目前資料流是否支援讀取。

C#
public override bool CanRead { get; }

屬性值

如果資料流支援讀取,則為 true;如果資料流已關閉或以唯寫存取開啟,則為 false

範例

下列範例示範 屬性的使用 CanRead 。 此程式代碼的輸出為「無法寫入 MyFile.txt」。若要取得輸出訊息「MyFile.txt 可以寫入和讀取。」,請在建構函式中FileStreamFileAccess 參數變更為 ReadWrite

C#
using System;
using System.IO;

class TestRW
{
    public static void Main(String[] args)
    {
        FileStream fs = new FileStream("MyFile.txt", FileMode.OpenOrCreate, FileAccess.Read);
        if (fs.CanRead && fs.CanWrite)
        {
            Console.WriteLine("MyFile.txt can be both written to and read from.");
        }
        else if (fs.CanRead)
        {
            Console.WriteLine("MyFile.txt is not writable.");
        }
    }
}

備註

如果衍生自 Stream 的類別不支援讀取, 則呼叫、 ReadByteBeginRead 方法會Read擲回 NotSupportedException

如果資料流已關閉,這個屬性會傳 false回 。

適用於

產品 版本
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.3, 1.4, 1.6, 2.0, 2.1
UWP 10.0

另請參閱