FileStream 类

定义

为文件提供 Stream,既支持同步读写操作,也支持异步读写操作。

public ref class FileStream : System::IO::Stream
public class FileStream : System.IO.Stream
[System.Runtime.InteropServices.ComVisible(true)]
public class FileStream : System.IO.Stream
type FileStream = class
    inherit Stream
[<System.Runtime.InteropServices.ComVisible(true)>]
type FileStream = class
    inherit Stream
Public Class FileStream
Inherits Stream
继承
FileStream
继承
派生
属性

示例

以下示例演示了一 FileStream 些构造函数。

using namespace System;
using namespace System::IO;
using namespace System::Text;

void AddText( FileStream^ fs, String^ value )
{
   array<Byte>^info = (gcnew UTF8Encoding( true ))->GetBytes( value );
   fs->Write( info, 0, info->Length );
}

int main()
{
   String^ path = "c:\\temp\\MyTest.txt";
   
   // Delete the file if it exists.
   if ( File::Exists( path ) )
   {
      File::Delete( path );
   }

   //Create the file.
   {
      FileStream^ fs = File::Create( path );
      try
      {
         AddText( fs, "This is some text" );
         AddText( fs, "This is some more text," );
         AddText( fs, "\r\nand this is on a new line" );
         AddText( fs, "\r\n\r\nThe following is a subset of characters:\r\n" );
         for ( int i = 1; i < 120; i++ )
         {
            AddText( fs, Convert::ToChar( i ).ToString() );
            
            //Split the output at every 10th character.
            if ( Math::IEEERemainder( Convert::ToDouble( i ), 10 ) == 0 )
            {
               AddText( fs, "\r\n" );
            }
         }
      }
      finally
      {
         if ( fs )
            delete (IDisposable^)fs;
      }
   }
   
   //Open the stream and read it back.
   {
      FileStream^ fs = File::OpenRead( path );
      try
      {
         array<Byte>^b = gcnew array<Byte>(1024);
         UTF8Encoding^ temp = gcnew UTF8Encoding( true );
         while ( fs->Read( b, 0, b->Length ) > 0 )
         {
            Console::WriteLine( temp->GetString( b ) );
         }
      }
      finally
      {
         if ( fs )
            delete (IDisposable^)fs;
      }
   }
}
using System;
using System.IO;
using System.Text;

class Test
{

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

        // Delete the file if it exists.
        if (File.Exists(path))
        {
            File.Delete(path);
        }

        //Create the file.
        using (FileStream fs = File.Create(path))
        {
            AddText(fs, "This is some text");
            AddText(fs, "This is some more text,");
            AddText(fs, "\r\nand this is on a new line");
            AddText(fs, "\r\n\r\nThe following is a subset of characters:\r\n");

            for (int i=1;i < 120;i++)
            {
                AddText(fs, Convert.ToChar(i).ToString());
            }
        }

        //Open the stream and read it back.
        using (FileStream fs = File.OpenRead(path))
        {
            byte[] b = new byte[1024];
            UTF8Encoding temp = new UTF8Encoding(true);
            int readLen;
            while ((readLen = fs.Read(b,0,b.Length)) > 0)
            {
                Console.WriteLine(temp.GetString(b,0,readLen));
            }
        }
    }

    private static void AddText(FileStream fs, string value)
    {
        byte[] info = new UTF8Encoding(true).GetBytes(value);
        fs.Write(info, 0, info.Length);
    }
}
open System
open System.IO
open System.Text

let addText (fs:FileStream) (value: string) =
    let info = UTF8Encoding(true).GetBytes value
    fs.Write(info, 0, info.Length);

let path = @"c:\temp\MyTest.txt"

// Delete the file if it exists.
if File.Exists path then
    File.Delete path

//Create the file.
do
    use fs = File.Create path

    addText fs "This is some text"
    addText fs "This is some more text,"
    addText fs "\r\nand this is on a new line"
    addText fs "\r\n\r\nThe following is a subset of characters:\r\n"

    for i = 1 to 119 do
        Convert.ToChar i
        |> string
        |> addText fs
    
do
    //Open the stream and read it back.
    use fs = File.OpenRead path
    let b = Array.zeroCreate 1024
    let temp = UTF8Encoding true
    let mutable readLen = fs.Read(b,0,b.Length);
    while readLen> 0 do
        printfn $"{temp.GetString(b,0,readLen)}"
        readLen <- fs.Read(b,0,b.Length)
Imports System.IO
Imports System.Text

Public Class Test

    Public Shared Sub Main()
        Dim path As String = "c:\temp\MyTest.txt"

        ' Delete the file if it exists.
        If File.Exists(path) Then
            File.Delete(path)
        End If

        'Create the file.
        Dim fs As FileStream = File.Create(path)

        AddText(fs, "This is some text")
        AddText(fs, "This is some more text,")
        AddText(fs, Environment.NewLine & "and this is on a new line")
        AddText(fs, Environment.NewLine & Environment.NewLine)
        AddText(fs, "The following is a subset of characters:" & Environment.NewLine)

        Dim i As Integer

        For i = 1 To 120
            AddText(fs, Convert.ToChar(i).ToString())

        Next

        fs.Close()

        'Open the stream and read it back.
        fs = File.OpenRead(path)
        Dim b(1023) As Byte
        Dim temp As UTF8Encoding = New UTF8Encoding(True)

        Do While fs.Read(b, 0, b.Length) > 0
            Console.WriteLine(temp.GetString(b))
        Loop

        fs.Close()
    End Sub

    Private Shared Sub AddText(ByVal fs As FileStream, ByVal value As String)
        Dim info As Byte() = New UTF8Encoding(True).GetBytes(value)
        fs.Write(info, 0, info.Length)
    End Sub
End Class

以下示例演示如何异步写入文件。 此代码在一个 WPF 应用中运行,该应用具有名为 UserInput 的 TextBlock 和一个连接到名为 Button_Click 的 Click 事件处理程序的按钮。 需要将文件路径更改为计算机上存在的文件。

using System;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.IO;

namespace WpfApplication1
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private async void Button_Click(object sender, RoutedEventArgs e)
        {
            UnicodeEncoding uniencoding = new UnicodeEncoding();
            string filename = @"c:\Users\exampleuser\Documents\userinputlog.txt";

            byte[] result = uniencoding.GetBytes(UserInput.Text);

            using (FileStream SourceStream = File.Open(filename, FileMode.OpenOrCreate))
            {
                SourceStream.Seek(0, SeekOrigin.End);
                await SourceStream.WriteAsync(result, 0, result.Length);
            }
        }
    }
}
Imports System.IO
Imports System.Text

Class MainWindow
    Private Async Sub Button_Click(sender As Object, e As RoutedEventArgs)
        Dim uniencoding As UnicodeEncoding = New UnicodeEncoding()
        Dim filename As String = "c:\Users\exampleuser\Documents\userinputlog.txt"

        Dim result As Byte() = uniencoding.GetBytes(UserInput.Text)

        Using SourceStream As FileStream = File.Open(filename, FileMode.OpenOrCreate)
            SourceStream.Seek(0, SeekOrigin.End)
            Await SourceStream.WriteAsync(result, 0, result.Length)
        End Using
    End Sub
End Class

注解

有关此 API 的详细信息,请参阅 FileStream 的补充 API 说明

构造函数

FileStream(IntPtr, FileAccess)
已过时.
已过时.
已过时.

使用指定的读/写权限为指定的文件句柄初始化 FileStream 类的新实例。

FileStream(IntPtr, FileAccess, Boolean)
已过时.
已过时.
已过时.

使用指定的读/写权限和 FileStream 实例所属权为指定的文件句柄初始化 FileStream 类的新实例。

FileStream(IntPtr, FileAccess, Boolean, Int32)
已过时.
已过时.
已过时.

使用指定的读/写权限、FileStream 实例所属权和缓冲区大小为指定的文件句柄初始化 FileStream 类的新实例。

FileStream(IntPtr, FileAccess, Boolean, Int32, Boolean)
已过时.
已过时.
已过时.

使用指定的读/写权限、FileStream 实例所属权、缓冲区大小和同步或异步状态为指定的文件句柄初始化 FileStream 类的新实例。

FileStream(SafeFileHandle, FileAccess)

使用指定的读/写权限为指定的文件句柄初始化 FileStream 类的新实例。

FileStream(SafeFileHandle, FileAccess, Int32)

使用指定的读/写权限和缓冲区大小为指定的文件句柄初始化 FileStream 类的新实例。

FileStream(SafeFileHandle, FileAccess, Int32, Boolean)

使用指定的读/写权限、缓冲区大小和同步或异步状态为指定的文件句柄初始化 FileStream 类的新实例。

FileStream(String, FileMode)

使用指定的路径和创建模式初始化 FileStream 类的新实例。

FileStream(String, FileMode, FileAccess)

使用指定的路径、创建模式和读/写权限初始化 FileStream 类的新实例。

FileStream(String, FileMode, FileAccess, FileShare)

使用指定的路径、创建模式、读/写权限和共享权限创建 FileStream 类的新实例。

FileStream(String, FileMode, FileAccess, FileShare, Int32)

用指定的路径、创建模式、读/写及共享权限和缓冲区大小初始化 FileStream 类的新实例。

FileStream(String, FileMode, FileAccess, FileShare, Int32, Boolean)

使用指定的路径、创建模式、读/写和共享权限、缓冲区大小和同步或异步状态初始化 FileStream 类的新实例。

FileStream(String, FileMode, FileAccess, FileShare, Int32, FileOptions)

使用指定的路径、创建模式、读/写和共享权限、其他 FileStreams 可以具有的对此文件的访问权限、缓冲区大小和附加文件选项初始化 FileStream 类的新实例。

FileStream(String, FileMode, FileSystemRights, FileShare, Int32, FileOptions)

使用指定的路径、创建模式、访问权限和共享权限、缓冲区大小和附加文件选项初始化 FileStream 类的新实例。

FileStream(String, FileMode, FileSystemRights, FileShare, Int32, FileOptions, FileSecurity)

使用指定的路径、创建模式、访问权限和共享权限、缓冲区大小、附加文件选项、访问控制和审核安全初始化 FileStream 类的新实例。

FileStream(String, FileStreamOptions)

使用指定的路径、创建模式、读/写和共享权限、缓冲区大小、其他文件选项、预分配大小以及其他 FileStreams 对同一文件的访问权限初始化 类的新实例 FileStream

属性

CanRead

获取一个值,该值指示当前流是否支持读取。

CanSeek

获取一个值,该值指示当前流是否支持查找。

CanTimeout

获取一个值,该值确定当前流是否可以超时。

(继承自 Stream)
CanWrite

获取一个值,该值指示当前流是否支持写入。

Handle
已过时.
已过时.
已过时.

获取当前 FileStream 对象所封装文件的操作系统文件句柄。

IsAsync

获取一个值,它指示 FileStream 是异步打开还是同步打开的。

Length

获取流的长度(以字节为单位)。

Name

获取 FileStream 中已打开的文件的绝对路径。

Position

获取或设置此流的当前位置。

ReadTimeout

获取或设置一个值(以毫秒为单位),该值确定流在超时前将尝试读取的时间。

(继承自 Stream)
SafeFileHandle

获取 SafeFileHandle 对象,它代表当前 FileStream 对象所封装的文件的操作系统文件句柄。

WriteTimeout

获取或设置一个值(以毫秒为单位),该值确定流在超时前将尝试写入多长时间。

(继承自 Stream)

方法

BeginRead(Byte[], Int32, Int32, AsyncCallback, Object)

开始异步读操作。 请考虑改用 ReadAsync(Byte[], Int32, Int32, CancellationToken)

BeginRead(Byte[], Int32, Int32, AsyncCallback, Object)

开始异步读操作。 (请考虑改用 ReadAsync(Byte[], Int32, Int32)。)

(继承自 Stream)
BeginWrite(Byte[], Int32, Int32, AsyncCallback, Object)

开始异步写操作。 请考虑改用 WriteAsync(Byte[], Int32, Int32, CancellationToken)

BeginWrite(Byte[], Int32, Int32, AsyncCallback, Object)

开始异步写操作。 (请考虑改用 WriteAsync(Byte[], Int32, Int32)。)

(继承自 Stream)
Close()

关闭当前流并释放与之关联的所有资源(如套接字和文件句柄)。

Close()

关闭当前流并释放与之关联的所有资源(如套接字和文件句柄)。 不直接调用此方法,而应确保流得以正确释放。

(继承自 Stream)
CopyTo(Stream)

从当前流中读取字节并将其写入到另一流中。 这两个流位置都以复制的字节数为高级。

(继承自 Stream)
CopyTo(Stream, Int32)

为文件提供 Stream,既支持同步读写操作,也支持异步读写操作。

CopyTo(Stream, Int32)

使用指定的缓冲区大小,从当前流中读取字节并将其写入到另一流中。 这两个流位置都以复制的字节数为高级。

(继承自 Stream)
CopyToAsync(Stream)

从当前流中异步读取字节并将其写入到另一个流中。 这两个流位置都以复制的字节数为高级。

(继承自 Stream)
CopyToAsync(Stream, CancellationToken)

通过指定的取消令牌,从当前流中异步读取字节并将其写入到另一个流中。 这两个流位置都以复制的字节数为高级。

(继承自 Stream)
CopyToAsync(Stream, Int32)

使用指定的缓冲区大小,从当前流中异步读取字节并将其写入到另一流中。 这两个流位置都以复制的字节数为高级。

(继承自 Stream)
CopyToAsync(Stream, Int32, CancellationToken)

使用指定的缓冲区大小和取消令牌,从当前文件流中异步读取字节并将其写入到另一个流中。

CopyToAsync(Stream, Int32, CancellationToken)

使用指定的缓冲区大小和取消令牌,从当前流中异步读取字节并将其写入到另一个流中。 这两个流位置都以复制的字节数为高级。

(继承自 Stream)
CreateObjRef(Type)

创建一个对象,该对象包含生成用于与远程对象进行通信的代理所需的全部相关信息。

(继承自 MarshalByRefObject)
CreateWaitHandle()
已过时.
已过时.
已过时.

分配 WaitHandle 对象。

(继承自 Stream)
Dispose()

释放由 Stream 使用的所有资源。

(继承自 Stream)
Dispose(Boolean)

释放由 FileStream 占用的非托管资源,还可以另外再释放托管资源。

DisposeAsync()

异步释放 FileStream 使用的非托管资源。

DisposeAsync()

异步释放 Stream 使用的非托管资源。

(继承自 Stream)
EndRead(IAsyncResult)

等待挂起的异步读操作完成。 (请考虑改用 ReadAsync(Byte[], Int32, Int32, CancellationToken)。)

EndRead(IAsyncResult)

等待挂起的异步读取完成。 (请考虑改用 ReadAsync(Byte[], Int32, Int32)。)

(继承自 Stream)
EndWrite(IAsyncResult)

结束异步写入操作,在 I/O 操作完成之前一直阻止。 (请考虑改用 WriteAsync(Byte[], Int32, Int32, CancellationToken)。)

EndWrite(IAsyncResult)

结束异步写操作。 (请考虑改用 WriteAsync(Byte[], Int32, Int32)。)

(继承自 Stream)
Equals(Object)

确定指定对象是否等于当前对象。

(继承自 Object)
Finalize()

确保垃圾回收器回收 FileStream 时释放资源并执行其他清理操作。

Flush()

清除此流的缓冲区,使得所有缓冲数据都写入到文件中。

Flush(Boolean)

清除此流的缓冲区,将所有缓冲数据都写入到文件中,并且也清除所有中间文件缓冲区。

FlushAsync()

异步清除此流的所有缓冲区并导致所有缓冲数据都写入基础设备中。

(继承自 Stream)
FlushAsync(CancellationToken)

异步清理此流的所有缓冲区,导致所有缓冲数据都写入基础设备,并且监控取消请求。

FlushAsync(CancellationToken)

异步清理此流的所有缓冲区,导致所有缓冲数据都写入基础设备,并且监控取消请求。

(继承自 Stream)
GetAccessControl()

获取 FileSecurity 对象,该对象封装当前 FileStream 对象所描述的文件的访问控制列表 (ACL) 项。

GetHashCode()

作为默认哈希函数。

(继承自 Object)
GetLifetimeService()
已过时.

检索控制此实例的生存期策略的当前生存期服务对象。

(继承自 MarshalByRefObject)
GetType()

获取当前实例的 Type

(继承自 Object)
InitializeLifetimeService()
已过时.

获取生存期服务对象来控制此实例的生存期策略。

(继承自 MarshalByRefObject)
Lock(Int64, Int64)

防止其他进程读取或写入 FileStream

MemberwiseClone()

创建当前 Object 的浅表副本。

(继承自 Object)
MemberwiseClone(Boolean)

创建当前 MarshalByRefObject 对象的浅表副本。

(继承自 MarshalByRefObject)
ObjectInvariant()
已过时.

提供对 Contract 的支持。

(继承自 Stream)
Read(Byte[], Int32, Int32)

从流中读取字节块并将该数据写入给定缓冲区中。

Read(Span<Byte>)

从当前文件流中读取字节序列,并在该文件流中按照读取的字节数提升位置。

Read(Span<Byte>)

当在派生类中重写时,从当前流读取字节序列,并将此流中的位置提升读取的字节数。

(继承自 Stream)
ReadAsync(Byte[], Int32, Int32)

从当前流异步读取字节序列,并将流中的位置提升读取的字节数。

(继承自 Stream)
ReadAsync(Byte[], Int32, Int32, CancellationToken)

从当前文件流异步读取字节的序列,将其写入从指定偏移量开始的字节数组,按读取的字节数向前移动文件流中的位置,并监视取消请求。

ReadAsync(Byte[], Int32, Int32, CancellationToken)

从当前流异步读取字节的序列,将流中的位置提升读取的字节数,并监视取消请求。

(继承自 Stream)
ReadAsync(Memory<Byte>, CancellationToken)

从当前文件流异步读取字节的序列,将其写入某内存区域,按读取的字节数向前移动文件流中的位置,并监视取消请求。

ReadAsync(Memory<Byte>, CancellationToken)

从当前流异步读取字节的序列,将流中的位置提升读取的字节数,并监视取消请求。

(继承自 Stream)
ReadAtLeast(Span<Byte>, Int32, Boolean)

从当前流中至少读取最小字节数,并按读取的字节数提升流中的位置。

(继承自 Stream)
ReadAtLeastAsync(Memory<Byte>, Int32, Boolean, CancellationToken)

从当前流异步读取至少最小字节数,将流中的位置按读取的字节数前进,并监视取消请求。

(继承自 Stream)
ReadByte()

从文件中读取一个字节,并将读取位置提升一个字节。

ReadExactly(Byte[], Int32, Int32)

count从当前流中读取字节数,并提升流中的位置。

(继承自 Stream)
ReadExactly(Span<Byte>)

从当前流中读取字节,并推进流中的位置, buffer 直到 填充 。

(继承自 Stream)
ReadExactlyAsync(Byte[], Int32, Int32, CancellationToken)

从当前流异步读取 count 字节数,推进流中的位置,并监视取消请求。

(继承自 Stream)
ReadExactlyAsync(Memory<Byte>, CancellationToken)

从当前流异步读取字节,推进流中的位置,直到 buffer 填充,并监视取消请求。

(继承自 Stream)
Seek(Int64, SeekOrigin)

将该流的当前位置设置为给定值。

SetAccessControl(FileSecurity)

FileSecurity 对象所描述的访问控制列表 (ACL) 项应用于当前 FileStream 对象所描述的文件。

SetLength(Int64)

将该流的长度设置为给定值。

ToString()

返回表示当前对象的字符串。

(继承自 Object)
Unlock(Int64, Int64)

允许其他进程访问以前锁定的某个文件的全部或部分。

Write(Byte[], Int32, Int32)

将字节块写入文件流。

Write(ReadOnlySpan<Byte>)

将字节的序列从只读范围写入当前文件流,并按写入的字节数向前移动此文件流中的当前位置。

Write(ReadOnlySpan<Byte>)

当在派生类中重写时,向当前流中写入字节序列,并将此流中的当前位置提升写入的字节数。

(继承自 Stream)
WriteAsync(Byte[], Int32, Int32)

将字节序列异步写入当前流,并将流的当前位置提升写入的字节数。

(继承自 Stream)
WriteAsync(Byte[], Int32, Int32, CancellationToken)

将字节的序列异步写入当前流,将该流中的当前位置向前移动写入的字节数,并监视取消请求。

WriteAsync(Byte[], Int32, Int32, CancellationToken)

将字节的序列异步写入当前流,将该流中的当前位置向前移动写入的字节数,并监视取消请求。

(继承自 Stream)
WriteAsync(ReadOnlyMemory<Byte>, CancellationToken)

将字节的序列从内存区域异步写入当前文件流,按写入的字节数向前移动该文件流中的当前位置,并监视取消请求。

WriteAsync(ReadOnlyMemory<Byte>, CancellationToken)

将字节的序列异步写入当前流,将该流中的当前位置向前移动写入的字节数,并监视取消请求。

(继承自 Stream)
WriteByte(Byte)

一个字节写入文件流中的当前位置。

显式接口实现

IDisposable.Dispose()

释放由 Stream 使用的所有资源。

(继承自 Stream)

扩展方法

GetAccessControl(FileStream)

返回文件的安全信息。

SetAccessControl(FileStream, FileSecurity)

更改现有文件的安全属性。

AsInputStream(Stream)

将适用于 Windows 应用商店应用的 .NET 中的托管流转换为 Windows 运行时中的输入流。

AsOutputStream(Stream)

将适用于 Windows 应用商店应用的 .NET 中的托管流转换为 Windows 运行时中的输出流。

AsRandomAccessStream(Stream)

将指定的流转换为随机访问流。

ConfigureAwait(IAsyncDisposable, Boolean)

配置如何执行从异步可处置项返回的任务的等待。

适用于

另请参阅