FileStream クラス

同期および非同期の読み取り操作と書き込み操作をサポートするファイル用の Stream を公開します。

この型のすべてのメンバの一覧については、FileStream メンバ を参照してください。

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

Public Class FileStream
   Inherits Stream
[C#]
public class FileStream : Stream
[C++]
public __gc class FileStream : public Stream
[JScript]
public class FileStream extends Stream

スレッドセーフ

この型の public static (Visual Basicでは Shared) のすべてのメンバは、マルチスレッド操作で安全に使用できます。インスタンスのメンバの場合は、スレッドセーフであるとは限りません。

解説

FileStream クラスは、ファイル システム上のファイルの読み取り、書き込み、オープン、クローズ、およびファイル関連のその他のオペレーティング システム ハンドル (パイプ、標準入力、標準出力など) の操作に使用します。読み取り操作と書込み操作は、同期または非同期のどちらかに指定できます。 FileStream バッファの入出力を使用するとパフォーマンスが向上します。

FileStream オブジェクトは、 Seek メソッドによるファイルへのランダム アクセスをサポートします。 Seek メソッドを使用すると、ファイル内の任意の位置に読み取り/書き込み位置を移動できます。これはバイト オフセット参照ポイントのパラメータで行います。バイト オフセットはシーク参照ポイントに対して相対的です。シーク参照ポイントを SeekOrigin クラスの 3 つのプロパティの指定に従って、基になるファイルの先頭、現在位置、または末尾のいずれかに指定できます。

メモ   ディスク ファイルは、常にランダム アクセスをサポートします。構築時に、基になるファイルの種類に応じて、 CanSeek プロパティが true または false に設定されます。具体的には、基になるファイルの種類が winbase.h で定義される FILE_TYPE_DISK の場合、 CanSeek プロパティは true に設定されます。それ以外の場合、 CanSeek プロパティは false に設定されます。

同期メソッドの ReadWrite 、および非同期メソッドの BeginReadBeginWriteEndReadEndWrite は、同期モードまたは非同期モードのどちらでも動作できますが、モードはこれらのメソッドのパフォーマンスに影響します。 FileStream は、既定ではファイルを同期的に開きますが、ファイルを非同期的に開く FileStream(IntPtr, FileAccess, Boolean, Int32, Boolean) コンストラクタと FileStream(String, FileMode, FileAccess, FileShare, Int32, Boolean) コンストラクタも用意されています。

ファイルの一部がロックされた状態でプロセスが終了した場合、またはロックが保留されているファイルを閉じた場合の動作は未定義です。

ディレクトリとその他のファイル操作については、 FileDirectoryPath の各クラスのトピックを参照してください。 File クラスは、ファイル パス、標準入力、標準出力、および標準エラー デバイスに基づいた FileStream オブジェクトの作成を主とする静的メソッドを持つユーティリティ クラスです。 MemoryStream クラスは、 FileStream と同様に、バイト配列と関数からストリームを作成します。

このクラスの使用例については、以下の「使用例」を参照してください。その他の一般的な I/O タスクまたは関連する 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

使用例

[Visual Basic, C#, C++] 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

[C#] 
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);
    }
}

[C++] 
#using <mscorlib.dll>

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

void AddText(FileStream* fs, String* value) {
    Byte info[] = (new UTF8Encoding(true))->GetBytes(value);
    fs->Write(info, 0, info->Length);
}

int main() {
    String* path = S"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, S"This is some text");
            AddText(fs, S"This is some more text,");
            AddText(fs, S"\r\nand this is on a new line");
            AddText(fs, S"\r\n\r\nThe following is a subset of characters:\r\n");

            for (int i=1;i < 120;i++) {
                AddText(fs, __box(Convert::ToChar(i))->ToString());

                //Split the output at every 10th character.
                if (Math::IEEERemainder(Convert::ToDouble(i), 10) == 0) {
                    AddText(fs, S"\r\n");
                }
            }
        } __finally {
            if (fs) __try_cast<IDisposable*>(fs)->Dispose();
        }
    }

    //Open the stream and read it back.
    {
        FileStream* fs = File::OpenRead(path);
        try {
            Byte b[] = new Byte[1024];
            UTF8Encoding* temp = new UTF8Encoding(true);
            while (fs->Read(b,0,b->Length) > 0) {
                Console::WriteLine(temp->GetString(b));
            }
        } __finally {
            if (fs) __try_cast<IDisposable*>(fs)->Dispose();
        }
    }
}

[Visual Basic, C#, C++] ファイルを開くか、ファイルが存在しない場合はファイルを作成して、そのファイルの末尾に情報を追加する例を次に示します。

 
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

[C#] 
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();
    }
}

[C++] 
#using <mscorlib.dll>

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

int main() {
    FileStream* fs = new FileStream(S"c:\\Variables.txt", FileMode::Append, FileAccess::Write, FileShare::Write);
    fs->Close();
    StreamWriter* sw = new StreamWriter(S"c:\\Variables.txt", true, Encoding::ASCII);
    String* NextLine=S"This is the appended line.";
    sw->Write(NextLine);
    sw->Close();
}

[JScript] JScript のサンプルはありません。Visual Basic、C#、および C++ のサンプルを表示するには、このページの左上隅にある言語のフィルタ ボタン 言語のフィルタ をクリックします。

必要条件

名前空間: System.IO

プラットフォーム: Windows 98, Windows NT 4.0, Windows Millennium Edition, Windows 2000, Windows XP Home Edition, Windows XP Professional, Windows Server 2003 ファミリ, .NET Compact Framework - Windows CE .NET

アセンブリ: Mscorlib (Mscorlib.dll 内)

参照

FileStream メンバ | System.IO 名前空間 | File | FileAccess | FileMode | FileShare | 入出力操作 | ファイルからのテキストの読み取り | ファイルへのテキストの書き込み | 基本のファイル I/O | 新しく作成したデータ ファイルの読み取りと書き込み