FileStream 类

公开以文件为主的 Stream,既支持同步读写操作,也支持异步读写操作。

**命名空间:**System.IO
**程序集:**mscorlib(在 mscorlib.dll 中)

语法

声明
<ComVisibleAttribute(True)> _
Public Class FileStream
    Inherits Stream
用法
Dim instance As FileStream
[ComVisibleAttribute(true)] 
public class FileStream : Stream
[ComVisibleAttribute(true)] 
public ref class FileStream : public Stream
/** @attribute ComVisibleAttribute(true) */ 
public class FileStream extends Stream
ComVisibleAttribute(true) 
public class FileStream extends Stream

备注

使用 FileStream 类对文件系统上的文件进行读取、写入、打开和关闭操作,并对其他与文件相关的操作系统句柄进行操作,如管道、标准输入和标准输出。读写操作可以指定为同步或异步操作。FileStream 对输入输出进行缓冲,从而提高性能。

FileStream 对象支持使用 Seek 方法对文件进行随机访问。Seek 允许将读取/写入位置移动到文件中的任意位置。这是通过字节偏移参考点参数完成的。字节偏移量是相对于查找参考点而言的,该参考点可以是基础文件的开始、当前位置或结尾,分别由 SeekOrigin 类的三个属性表示。

提示

磁盘文件始终支持随机访问。在构造时,CanSeek 属性值设置为 truefalse,具体取决于基础文件类型。具体地说,就是当基础文件类型是 FILE_TYPE_DISK(如 winbase.h 中所定义)时,CanSeek 属性值为 true。否则,CanSeek 属性值为 false

虽然同步方法 ReadWrite 以及异步方法 BeginReadBeginWriteEndReadEndWrite 在同步或异步模式下都可以工作,但模式会影响这些方法的性能。FileStream 默认情况下以同步方式打开文件,但提供 FileStream(String,FileMode,FileAccess,FileShare,Int32,Boolean) 构造函数以异步方式打开文件。

如果进程因文件的一部分锁定而终止或者关闭具有未解除锁定的文件,则行为是未定义的。

请确保对所有 FileStream 对象调用 Dispose 方法,特别是在磁盘空间有限的环境中。如果没有可用的磁盘空间并且在终止 FileStream 之前没有调用 Dispose 方法,则执行 IO 操作会引发异常。

有关目录和其他文件操作的信息,请参见 FileDirectoryPath 类。File 类是实用工具类,所带静态方法主要用于根据文件路径和标准输入、标准输出以及标准错误设备创建 FileStream 对象。MemoryStream 类通过字节数组创建流,而且功能与 FileStream 类似。

下表列出了其他典型或相关的 I/O 任务的示例。

若要执行此操作...

请参见本主题中的示例...

创建文本文件。

如何:向文件写入文本

写入文本文件。

如何:向文件写入文本

读取文本文件。

如何:从文件读取文本

向文件中追加文本。

如何:打开并追加到日志文件

File.AppendText

FileInfo.AppendText

重命名或移动文件。

File.Move

FileInfo.MoveTo

删除文件。

File.Delete

FileInfo.Delete

复制文件。

File.Copy

FileInfo.CopyTo

获取文件大小。

FileInfo.Length

获取文件属性。

File.GetAttributes

设置文件属性。

File.SetAttributes

确定文件是否存在。

File.Exists

读取二进制文件。

如何:对新建的数据文件进行读取和写入

写入二进制文件。

如何:对新建的数据文件进行读取和写入

检索文件扩展名。

Path.GetExtension

检索文件的完全限定路径。

Path.GetFullPath

检索路径中的文件名和扩展名。

Path.GetFileName

更改文件扩展名。

Path.ChangeExtension

流位置更改检测

如果 FileStream 对象没有独占持有其句柄,则另一个线程可以并发访问该文件句柄并更改与该文件句柄关联的操作系统的文件指针的位置。在这种情况下,FileStream 对象中的缓存位置和缓冲区中的缓存数据会受到危害。FileStream 对象会对访问缓存缓冲区的方法执行例行检查,以确保操作系统的句柄位置与 FileStream 对象使用的缓存位置相同。

如果在调用 Read 方法时检测到句柄位置发生意外更改,则 .NET Framework 会丢弃缓冲区的内容并从文件重新读取流。根据文件大小和任何其他可能影响文件流位置的进程,这可能会对性能产生影响。

如果在调用 Write 方法时检测到句柄位置发生意外更改,则丢弃缓冲区的内容并引发 IOException

访问 SafeFileHandle 属性以公开句柄或为 FileStream 对象在其构造函数中提供 SafeFileHandle 属性时,FileStream 对象不会独占持有其句柄。

示例

下面的示例演示一些 FileStream 构造函数的用法。

Imports System
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())

            'Split the output at every 10th character.
            If Math.IEEERemainder(Convert.ToDouble(i), 10) = 0 Then
                AddText(fs, Environment.NewLine)
            End If
        Next

        fs.Close()

        'Open the stream and read it back.
        fs = File.OpenRead(path)
        Dim b(1024) 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
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());

                //Split the output at every 10th character.
                if (Math.IEEERemainder(Convert.ToDouble(i), 10) == 0) 
                {
                    AddText(fs, "\r\n");
                }
            }
        }

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

    private static void AddText(FileStream fs, string value) 
    {
        byte[] info = new UTF8Encoding(true).GetBytes(value);
        fs.Write(info, 0, info.Length);
    }
}
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;
      }
   }
}
import System.*;
import System.IO.*;
import System.Text.*;

class Test
{
    public static void main(String[] args)
    {
        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, System.Convert.ToString((char)i));

                    //Split the output at every 10th character.
                    if (Math.IEEEremainder(Convert.ToDouble(i), 10) == 0) {
                        AddText(fs, "\r\n");
                    }
                }
            }
            finally {
                fs.Dispose();
            }
        }
        //Open the stream and read it back.
        {
            FileStream fs = File.OpenRead(path);
            try {
                ubyte b[] = new ubyte[1024];
                UTF8Encoding temp = new UTF8Encoding(true);
                while (fs.Read(b, 0, b.length) > 0) {
                    Console.WriteLine(temp.GetString(b));
                }
            }
            finally {
                fs.Dispose();
            }
        }
    } //main

    private static void AddText(FileStream fs, String value)
    {
        ubyte info[] = (new UTF8Encoding(true)).GetBytes(value);
        fs.Write(info, 0, info.length);
    } //AddText
} //Test

下面的示例打开一个文件(如果文件不存在则创建该文件)并将信息追加到文件末尾。

Imports System
Imports System.IO
Imports System.Text

Class FSOpenWrite

    Public Shared Sub Main()
        Dim fs As New FileStream("c:\Variables.txt", FileMode.Append, FileAccess.Write, FileShare.Write)
        fs.Close()
        Dim sw As New StreamWriter("c:\Variables.txt", True, Encoding.ASCII)
        Dim NextLine As String = "This is the appended text."
        sw.Write(NextLine)
        sw.Close()
    End Sub 'Main
End Class 'FSOpenWrite
using System;
using System.IO;
using System.Text;

class FSOpenWrite
{
    public static void Main()
    {
        FileStream fs=new FileStream("c:\\Variables.txt", FileMode.Append, FileAccess.Write, FileShare.Write);
        fs.Close();
        StreamWriter sw=new StreamWriter("c:\\Variables.txt", true, Encoding.ASCII);
        string NextLine="This is the appended line.";
        sw.Write(NextLine);
        sw.Close();
    }
}
using namespace System;
using namespace System::IO;
using namespace System::Text;
int main()
{
   FileStream^ fs = gcnew FileStream( "c:\\Variables.txt",FileMode::Append,FileAccess::Write,FileShare::Write );
   fs->Close();
   StreamWriter^ sw = gcnew StreamWriter( "c:\\Variables.txt",true,Encoding::ASCII );
   String^ NextLine = "This is the appended line.";
   sw->Write( NextLine );
   sw->Close();
}

继承层次结构

System.Object
   System.MarshalByRefObject
     System.IO.Stream
      System.IO.FileStream
         System.IO.IsolatedStorage.IsolatedStorageFileStream

线程安全

此类型的任何公共静态(Visual Basic 中的 Shared)成员都是线程安全的,但不保证所有实例成员都是线程安全的。

平台

Windows 98、Windows 2000 SP4、Windows CE、Windows Millennium Edition、Windows Mobile for Pocket PC、Windows Mobile for Smartphone、Windows Server 2003、Windows XP Media Center Edition、Windows XP Professional x64 Edition、Windows XP SP2、Windows XP Starter Edition

.NET Framework 并不是对每个平台的所有版本都提供支持。有关受支持版本的列表,请参见系统要求

版本信息

.NET Framework

受以下版本支持:2.0、1.1、1.0

.NET Compact Framework

受以下版本支持:2.0、1.0

请参见

参考

FileStream 成员
System.IO 命名空间
File 类
FileAccess 枚举
FileMode 枚举
FileShare 枚举

其他资源

文件和流 I/O
如何:从文件读取文本
如何:向文件写入文本
基本的文件 I/O
如何:对新建的数据文件进行读取和写入