FileStream 类
定义
重要
一些信息与预发行产品相关,相应产品在发行之前可能会进行重大修改。 对于此处提供的信息,Microsoft 不作任何明示或暗示的担保。
为文件提供 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 些构造函数。
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
注解
FileStream使用 类读取、写入、打开和关闭文件系统上的文件,并操作其他与文件相关的操作系统句柄,包括管道、标准输入和标准输出。 可以使用 Read、 Write、 CopyTo和 Flush 方法执行同步操作,或使用 ReadAsync、 WriteAsync、 CopyToAsync和 FlushAsync 方法执行异步操作。 使用异步方法执行资源密集型文件操作,而不会阻止主线程。 在 Windows 8.x 应用商店应用或桌面应用中一个耗时的流操作可能阻塞 UI 线程并让应用看起来好像不工作时,这种性能的考虑就显得尤为重要了。 FileStream 缓冲输入和输出以提高性能。
重要
此类型实现 IDisposable 接口。 在使用完类型后,您应直接或间接释放类型。 若要直接释放类型,请在 try
/catch
块中调用其 Dispose 方法。 若要间接释放类型,请使用 using
(在 C# 中)或 Using
(在 Visual Basic 中)等语言构造。 有关详细信息,请参阅 IDisposable 接口主题中的“使用实现 IDisposable 的对象”一节。
属性 IsAsync 检测文件句柄是否已异步打开。 使用具有 isAsync
、 或 options
参数的构造函数创建 类的FileStream实例时,useAsync
可以指定此值。 当 属性为 true
时,流利用重叠的 I/O 以异步方式执行文件操作。 但是, IsAsync 属性不一定是 true
来调用 ReadAsync、 WriteAsync或 CopyToAsync 方法。 IsAsync当 属性为 false
并且你调用异步读取和写入操作时,UI 线程仍不会被阻止,但实际 I/O 操作是同步执行的。
方法 Seek 支持对文件的随机访问。 Seek 允许将读/写位置移动到文件中的任何位置。 这是使用字节偏移参考点参数完成的。 字节偏移量相对于搜寻参考点,该参考点可以是基础文件的开头、当前位置或末尾,如 枚举的三个 SeekOrigin 成员所表示。
注意
磁盘文件始终支持随机访问。 在构造时, CanSeek 属性值设置为 true
或 false
,具体取决于基础文件类型。 如果基础文件类型是 winbase.h 中定义的FILE_TYPE_DISK,则 CanSeek 属性值为 true
。 否则, CanSeek 属性值为 false
。
如果进程终止并锁定了文件的一部分,或者关闭了具有未完成锁的文件,则行为未定义。
有关目录操作和其他文件操作,请参阅 File、 Directory和 Path 类。 类 File 是一个实用工具类,其静态方法主要用于基于文件路径创建 FileStream 对象。 类 MemoryStream 从字节数组创建流, FileStream 类似于 类。
有关常见文件和目录操作的列表,请参阅 常见 I/O 任务。
检测流位置更改
当对象 FileStream 在其句柄上没有独占保留时,另一个线程可以同时访问文件句柄,并更改与文件句柄关联的操作系统文件指针的位置。 在这种情况下,对象中的 FileStream 缓存位置和缓冲区中的缓存数据可能会受到威胁。 对象 FileStream 定期对访问缓存缓冲区的方法执行检查,以确保操作系统的句柄位置与对象使用的 FileStream 缓存位置相同。
如果在调用 Read 方法时检测到句柄位置的意外更改,.NET Framework放弃缓冲区的内容,并从文件中再次读取流。 这可能会影响性能,具体取决于文件的大小以及可能影响文件流位置的任何其他进程。
如果在调用 Write 方法时检测到句柄位置的意外更改,则会丢弃缓冲区的内容并 IOException 引发异常。
FileStream当访问属性以公开句柄或FileStream对象在其构造函数中为对象提供SafeFileHandle属性时SafeFileHandle,对象的句柄上不会有独占保留。
构造函数
属性
CanRead |
获取一个值,该值指示当前流是否支持读取。 |
CanSeek |
获取一个值,该值指示当前流是否支持查找。 |
CanTimeout |
获取一个值,该值确定当前流是否可以超时。 (继承自 Stream) |
CanWrite |
获取一个值,该值指示当前流是否支持写入。 |
Handle |
已过时。
已过时。
已过时。
已过时。
获取当前 |
IsAsync |
获取一个值,它指示 |
Length |
获取流的长度(以字节为单位)。 |
Name |
获取 |
Position |
获取或设置此流的当前位置。 |
ReadTimeout |
获取或设置一个值(以毫秒为单位),该值确定流在超时前将尝试读取的时间。 (继承自 Stream) |
SafeFileHandle |
获取 SafeFileHandle 对象,它代表当前 FileStream 对象所封装的文件的操作系统文件句柄。 |
WriteTimeout |
获取或设置一个值(以毫秒为单位),该值确定流在超时前将尝试写入多长时间。 (继承自 Stream) |
方法
显式接口实现
IDisposable.Dispose() |
释放由 Stream 使用的所有资源。 (继承自 Stream) |
扩展方法
GetAccessControl(FileStream) |
返回文件的安全信息。 |
SetAccessControl(FileStream, FileSecurity) |
更改现有文件的安全属性。 |
AsInputStream(Stream) |
将适用于 Windows 应用商店应用的 .NET 中的托管流转换为 Windows 运行时中的输入流。 |
AsOutputStream(Stream) |
将适用于 Windows 应用商店应用的 .NET 中的托管流转换为 Windows 运行时中的输出流。 |
AsRandomAccessStream(Stream) |
将指定的流转换为随机访问流。 |
ConfigureAwait(IAsyncDisposable, Boolean) |
配置如何执行从异步可处置项返回的任务的等待。 |