FileStream クラス
アセンブリ: mscorlib (mscorlib.dll 内)
構文
解説
FileStream クラスは、ファイル システム上のファイルの読み取り、書き込み、オープン、クローズ、およびファイル関連のその他のオペレーティング システム ハンドル (パイプ、標準入力、標準出力など) の操作に使用します。読み取り操作と書き込み操作は、同期または非同期のどちらかに指定できます。FileStream バッファの入出力を使用するとパフォーマンスが向上します。
FileStream オブジェクトは、Seek メソッドによるファイルへのランダム アクセスをサポートします。Seek メソッドを使用すると、ファイル内の任意の位置に読み取り/書き込み位置を移動できます。これはバイト オフセット参照ポイントのパラメータで行います。バイト オフセットはシーク参照ポイントに対して相対的です。シーク参照ポイントを SeekOrigin クラスの 3 つのプロパティの指定に従って、基になるファイルの先頭、現在位置、または末尾のいずれかに指定できます。
メモ |
---|
ディスク ファイルは、常にランダム アクセスをサポートします。構築時に、基になるファイルの種類に応じて、CanSeek プロパティが true または false に設定されます。具体的には、基になるファイルの種類が winbase.h で定義される FILE_TYPE_DISK の場合、CanSeek プロパティは true に設定されます。それ以外の場合、CanSeek プロパティは false に設定されます。 |
同期メソッドの Read と Write、および非同期メソッドの BeginRead、BeginWrite、EndRead、EndWrite は、同期モードまたは非同期モードのどちらでも動作できますが、モードはこれらのメソッドのパフォーマンスに影響します。FileStream は、既定ではファイルを同期的に開きますが、ファイルを非同期的に開く FileStream(String,FileMode,FileAccess,FileShare,Int32,Boolean) コンストラクタも用意されています。
ファイルの一部がロックされた状態でプロセスが終了した場合、またはロックが保留されているファイルを閉じた場合の動作は未定義です。
特にディスク容量が制限された環境では、すべての FileStream オブジェクトに対して、Dispose メソッドを必ず呼び出します。使用できるディスク容量がなく、FileStream を終了する前に Dispose メソッドが呼び出されていない場合、IO 操作を実行すると例外が発生する可能性があります。
ディレクトリとその他のファイル操作については、File、Directory、Path の各クラスのトピックを参照してください。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 | |
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.MarshalByRefObject
System.IO.Stream
System.IO.FileStream
System.IO.IsolatedStorage.IsolatedStorageFileStream
プラットフォーム
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 によってサポートされていないバージョンがあります。サポートされているバージョンについては、「システム要件」を参照してください。
参照
- FileStream クラスのページへのリンク