FileStream.CanWrite 属性
定义
重要
一些信息与预发行产品相关,相应产品在发行之前可能会进行重大修改。 对于此处提供的信息,Microsoft 不作任何明示或暗示的担保。
获取一个值,该值指示当前流是否支持写入。
public:
virtual property bool CanWrite { bool get(); };
public override bool CanWrite { get; }
member this.CanWrite : bool
Public Overrides ReadOnly Property CanWrite As Boolean
属性值
true 如果流支持写入,则为 false 如果流已关闭或已打开,则为只读访问权限。
示例
以下示例使用 CanWrite 该属性检查流是否支持写入。
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);
}
}
}
}
open System.IO
let path = @"c:\temp\MyTest.txt"
// Ensure that the file is readonly.
File.SetAttributes(path, File.GetAttributes path ||| FileAttributes.ReadOnly)
//Create the file.
do
use fs = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Read)
if fs.CanWrite then
printfn $"The stream for file {path} is writable."
else
printfn $"The stream for file {path} is not writable."
Imports System.IO
Public Class Test
Public Shared Sub Main()
Dim path As String = "c:\temp\MyTest.txt"
'Ensure that the file is readonly.
File.SetAttributes(path, File.GetAttributes(path) Or FileAttributes.ReadOnly)
'Create the file.
Dim fs As FileStream = New FileStream(path, FileMode.OpenOrCreate, FileAccess.Read)
If fs.CanWrite Then
Console.WriteLine("The stream connected to {0} is writable.", path)
Else
Console.WriteLine("The stream connected to {0} is not writable.", path)
End If
fs.Close()
End Sub
End Class
下面是使用该属性的示例 CanWrite 。 此代码的输出为“MyFile.txt 可写”。若要获取输出消息“MyFile.txt 可以写入和读取。”,请将 FileAccess 参数更改为 ReadWrite 构造函数中的 FileStream 参数。
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.");
}
}
}
open System.IO
let fs = new FileStream("MyFile.txt", FileMode.OpenOrCreate, FileAccess.Write)
if fs.CanRead && fs.CanWrite then
printfn "MyFile.txt can be both written to and read from."
elif fs.CanWrite then
printfn "MyFile.txt is writable."
Imports System.IO
Class TestRW
Public Shared Sub Main()
Dim fs As New FileStream("MyFile.txt", FileMode.OpenOrCreate, FileAccess.Write)
If fs.CanRead And fs.CanWrite Then
Console.WriteLine("MyFile.txt can be both written to and read from.")
ElseIf fs.CanWrite Then
Console.WriteLine("MyFile.txt is writable.")
End If
End Sub
End Class
注解
如果派生自Stream的类不支持写入、调用SetLength、WriteBeginWrite或WriteByte引发 。NotSupportedException
如果流已关闭,则此属性返回 false。