英語で読む

次の方法で共有


FileStream.CanWrite プロパティ

定義

現在のストリームが書き込みをサポートしているかどうかを示す値を取得します。

C#
public override bool CanWrite { get; }

プロパティ値

ストリームが書き込みをサポートしている場合は true。ストリームが閉じているか、読み取り専用アクセスで開かれた場合は false

次の例では、 プロパティをCanWrite使用して、ストリームが書き込みをサポートしているかどうかをチェックします。

C#
using System;
using System.IO;
using System.Text;

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

        // Ensure that the file is readonly.
        File.SetAttributes(path, File.GetAttributes(path) | FileAttributes.ReadOnly);

        //Create the file.
        using (FileStream fs = new FileStream (path, FileMode.OpenOrCreate, FileAccess.Read))
        {
            if (fs.CanWrite)
            {
                Console.WriteLine("The stream for file {0} is writable.", path);
            }
            else
            {
                Console.WriteLine("The stream for file {0} is not writable.", path);
            }
        }
    }
}

プロパティを使用する例を次に CanWrite 示します。 このコードの出力は"MyFile.txt 書き込み可能" です。"MyFile.txt の書き込みと読み取りの両方が可能です"という出力メッセージを取得するには、コンストラクターで FileStream パラメーターを FileAccessReadWrite変更します。

C#
using System;
using System.IO;

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

注釈

からStream派生したクラスが書き込みをサポートしていない場合は、 、WriteBeginWrite、または WriteByteSetLength呼び出しによって が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

こちらもご覧ください