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 コンストラクタ (IntPtr, FileAccess, Boolean, Int32, Boolean)
メモ : このコンストラクタは、互換性のために残されています。
FileStream クラスの新しいインスタンスを、指定した読み取り/書き込みアクセス許可、FileStream インスタンスの所有権、バッファ サイズ、および同期状態または非同期状態を使用して、指定したファイル ハンドル用に初期化します。 名前空間: System.IOアセンブリ: mscorlib (mscorlib.dll 内)

<ObsoleteAttribute("This constructor has been deprecated. Please use new FileStream(SafeFileHandle handle, FileAccess access, int bufferSize, bool isAsync) instead, and optionally make a new SafeFileHandle with ownsHandle=false if needed. http://go.microsoft.com/fwlink/?linkid=14202")> _ Public Sub New ( _ handle As IntPtr, _ access As FileAccess, _ ownsHandle As Boolean, _ bufferSize As Integer, _ isAsync As Boolean _ )
Dim handle As IntPtr Dim access As FileAccess Dim ownsHandle As Boolean Dim bufferSize As Integer Dim isAsync As Boolean Dim instance As New FileStream(handle, access, ownsHandle, bufferSize, isAsync)
[ObsoleteAttribute("This constructor has been deprecated. Please use new FileStream(SafeFileHandle handle, FileAccess access, int bufferSize, bool isAsync) instead, and optionally make a new SafeFileHandle with ownsHandle=false if needed. http://go.microsoft.com/fwlink/?linkid=14202")] public FileStream ( IntPtr handle, FileAccess access, bool ownsHandle, int bufferSize, bool isAsync )
[ObsoleteAttribute(L"This constructor has been deprecated. Please use new FileStream(SafeFileHandle handle, FileAccess access, int bufferSize, bool isAsync) instead, and optionally make a new SafeFileHandle with ownsHandle=false if needed. http://go.microsoft.com/fwlink/?linkid=14202")] public: FileStream ( IntPtr handle, FileAccess access, bool ownsHandle, int bufferSize, bool isAsync )
/** @attribute ObsoleteAttribute("This constructor has been deprecated. Please use new FileStream(SafeFileHandle handle, FileAccess access, int bufferSize, bool isAsync) instead, and optionally make a new SafeFileHandle with ownsHandle=false if needed. http://go.microsoft.com/fwlink/?linkid=14202") */ public FileStream ( IntPtr handle, FileAccess access, boolean ownsHandle, int bufferSize, boolean isAsync )
ObsoleteAttribute("This constructor has been deprecated. Please use new FileStream(SafeFileHandle handle, FileAccess access, int bufferSize, bool isAsync) instead, and optionally make a new SafeFileHandle with ownsHandle=false if needed. http://go.microsoft.com/fwlink/?linkid=14202") public function FileStream ( handle : IntPtr, access : FileAccess, ownsHandle : boolean, bufferSize : int, isAsync : boolean )

例外の種類 | 条件 |
---|---|
ArgumentOutOfRangeException | access が FileAccess.Read 未満であるか、FileAccess.ReadWrite 以上であるか、または bufferSize が 0 以下です。 |
ArgumentException | |
IOException | または |
SecurityException | |
UnauthorizedAccessException | access が Write または ReadWrite であるのに、ファイル ハンドルが読み取り専用に設定されているなど、指定したファイル ハンドルに対する access 要求がオペレーティング システムで許可されません。 |

FileStream オブジェクトには、ファイルへの指定したアクセス権が付与されます。ハンドルの所有権は、指定されているとおりになります。この FileStream がハンドルを所有している場合は、Close メソッドの呼び出しによって、ハンドルも閉じられます。特に、そのファイルのハンドル カウントがデクリメントされます。FileStream オブジェクトには、指定したバッファ サイズが付与されます。
FileStream は、ハンドルを排他的に制御していると見なされます。FileStream がハンドルも保持しているときに、読み取り、書き込み、またはシークを実行すると、データが破損することがあります。データを保護するために、ハンドルを使用する前に Flush を呼び出し、ハンドルの使用後は Close 以外のメソッドを呼び出さないようにします。または、この FileStream コンストラクタを呼び出す前に、ハンドルに対して読み取りと書き込みを行います。
FileShare パラメータを指定しないタイプの FileStream コンストラクタに対しては、FileShare.Read が既定値です。
![]() |
---|
特定のカルチャ設定で文字セットをコンパイルし、同じ文字を異なるカルチャ設定で取得すると、文字が正しく解釈されない場合があり、例外がスローされることもあります。 |
その他の一般的な 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 |


Windows 98, Windows 2000 SP4, Windows Millennium Edition, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition
開発プラットフォームの中には、.NET Framework によってサポートされていないバージョンがあります。サポートされているバージョンについては、「システム要件」を参照してください。


FileStream コンストラクタ (String, FileMode, FileSystemRights, FileShare, Int32, FileOptions)
アセンブリ: mscorlib (mscorlib.dll 内)

Public Sub New ( _ path As String, _ mode As FileMode, _ rights As FileSystemRights, _ share As FileShare, _ bufferSize As Integer, _ options As FileOptions _ )
Dim path As String Dim mode As FileMode Dim rights As FileSystemRights Dim share As FileShare Dim bufferSize As Integer Dim options As FileOptions Dim instance As New FileStream(path, mode, rights, share, bufferSize, options)
public FileStream ( string path, FileMode mode, FileSystemRights rights, FileShare share, int bufferSize, FileOptions options )
public: FileStream ( String^ path, FileMode mode, FileSystemRights rights, FileShare share, int bufferSize, FileOptions options )
public FileStream ( String path, FileMode mode, FileSystemRights rights, FileShare share, int bufferSize, FileOptions options )
public function FileStream ( path : String, mode : FileMode, rights : FileSystemRights, share : FileShare, bufferSize : int, options : FileOptions )

例外の種類 | 条件 |
---|---|
ArgumentNullException | path が null 参照 (Visual Basic では Nothing) です。 |
ArgumentException | path が空の文字列 ("") か、空白しか含んでいないか、無効な文字を 1 つ以上含んでいます。 または path がファイル以外のデバイスを参照しています (NTFS 環境の "con:"、"com1:"、"lpt1:" など)。 |
NotSupportedException | path がファイル以外のデバイスを参照しています (NTFS 以外の環境の "con:"、"com1:"、"lpt1:" など)。 |
ArgumentException | |
ArgumentOutOfRangeException | bufferSize が負の値またはゼロです。 または |
FileNotFoundException | ファイルが見つかりません。たとえば、mode が FileMode.Truncate または FileMode.Open の場合に、path で指定されたファイルが存在しません。これらのモードでは、ファイルが既に存在している必要があります。 |
PlatformNotSupportedException | 現在のオペレーティング システムは Windows NT 以降ではありません。 |
IOException | FileMode.CreateNew が指定されているのに、path で指定したファイルが既に存在していることなどが原因で I/O エラーが発生しました。 または |
SecurityException | |
DirectoryNotFoundException | |
UnauthorizedAccessException | access が Write または ReadWrite であるのに、ファイルまたはディレクトリが読み取り専用に設定されているなど、指定した path に対する access 要求がオペレーティング システムで許可されません。 |
PathTooLongException | 指定した path、ファイル名、またはその両方がシステム定義の最大長を超えています。たとえば、Windows ベースのプラットフォームの場合、パスの長さは 248 文字未満、ファイル名の長さは 260 文字未満である必要があります。 |

.NET Framework では、"\\.\PHYSICALDRIVE0" など、デバイス名を指定したパスを使用して物理ディスクに直接アクセスすることはできません。
この FileStream コンストラクタを使用して、ファイルの作成時のアクセス権を適用します。既存のファイルに対する権限にアクセスしたり変更したりするには、GetAccessControl メソッドおよび SetAccessControl メソッドの使用を検討してください。
fileOptions パラメータを使用すると、FileStream オブジェクトの作成時に活用できる、より高度な操作を利用できます。
path パラメータにはファイル名も指定できます。このファイルには、UNC 共有のファイルも含まれます。
![]() |
---|
特定のカルチャ設定で文字セットをコンパイルし、同じ文字を異なるカルチャ設定で取得すると、文字が正しく解釈されない場合があり、例外がスローされることもあります。 |
その他の一般的な 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 |


Windows 98, Windows 2000 SP4, Windows Millennium Edition, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition
開発プラットフォームの中には、.NET Framework によってサポートされていないバージョンがあります。サポートされているバージョンについては、「システム要件」を参照してください。


FileStream コンストラクタ (String, FileMode, FileSystemRights, FileShare, Int32, FileOptions, FileSecurity)
アセンブリ: mscorlib (mscorlib.dll 内)

Public Sub New ( _ path As String, _ mode As FileMode, _ rights As FileSystemRights, _ share As FileShare, _ bufferSize As Integer, _ options As FileOptions, _ fileSecurity As FileSecurity _ )
Dim path As String Dim mode As FileMode Dim rights As FileSystemRights Dim share As FileShare Dim bufferSize As Integer Dim options As FileOptions Dim fileSecurity As FileSecurity Dim instance As New FileStream(path, mode, rights, share, bufferSize, options, fileSecurity)
public FileStream ( string path, FileMode mode, FileSystemRights rights, FileShare share, int bufferSize, FileOptions options, FileSecurity fileSecurity )
public: FileStream ( String^ path, FileMode mode, FileSystemRights rights, FileShare share, int bufferSize, FileOptions options, FileSecurity^ fileSecurity )
public FileStream ( String path, FileMode mode, FileSystemRights rights, FileShare share, int bufferSize, FileOptions options, FileSecurity fileSecurity )
public function FileStream ( path : String, mode : FileMode, rights : FileSystemRights, share : FileShare, bufferSize : int, options : FileOptions, fileSecurity : FileSecurity )

例外の種類 | 条件 |
---|---|
ArgumentNullException | path が null 参照 (Visual Basic では Nothing) です。 |
ArgumentException | path が空の文字列 ("") か、空白しか含んでいないか、無効な文字を 1 つ以上含んでいます。 または path がファイル以外のデバイスを参照しています (NTFS 環境の "con:"、"com1:"、"lpt1:" など)。 |
NotSupportedException | path がファイル以外のデバイスを参照しています (NTFS 以外の環境の "con:"、"com1:"、"lpt1:" など)。 |
ArgumentException | |
ArgumentOutOfRangeException | bufferSize が負の値またはゼロです。 または |
FileNotFoundException | ファイルが見つかりません。たとえば、mode が FileMode.Truncate または FileMode.Open の場合に、path で指定されたファイルが存在しません。これらのモードでは、ファイルが既に存在している必要があります。 |
IOException | FileMode.CreateNew が指定されているのに、path で指定したファイルが既に存在していることなどが原因で I/O エラーが発生しました。 または |
SecurityException | |
DirectoryNotFoundException | |
UnauthorizedAccessException | access が Write または ReadWrite であるのに、ファイルまたはディレクトリが読み取り専用に設定されているなど、指定した path に対する access 要求がオペレーティング システムで許可されません。 |
PathTooLongException | 指定した path、ファイル名、またはその両方がシステム定義の最大長を超えています。たとえば、Windows ベースのプラットフォームの場合、パスの長さは 248 文字未満、ファイル名の長さは 260 文字未満である必要があります。 |
PlatformNotSupportedException | 現在のオペレーティング システムは Windows NT 以降ではありません。 |

.NET Framework では、"\\.\PHYSICALDRIVE0" など、デバイス名を指定したパスを使用して物理ディスクに直接アクセスすることはできません。
この FileStream コンストラクタを使用して、ファイルの作成時のアクセス権を適用します。既存のファイルに対する権限にアクセスしたり変更したりするには、GetAccessControl メソッドおよび SetAccessControl メソッドの使用を検討してください。
fileOptions パラメータを使用すると、FileStream オブジェクトの作成時に活用できる、より高度な操作を利用できます。
path パラメータにはファイル名も指定できます。このファイルには、UNC 共有のファイルも含まれます。
![]() |
---|
特定のカルチャ設定で文字セットをコンパイルし、同じ文字を異なるカルチャ設定で取得すると、文字が正しく解釈されない場合があり、例外がスローされることもあります。 |
その他の一般的な 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 オブジェクトを使用して、ファイルにデータを書き込み、次にデータを読み取る例を次に示します。
Imports System Imports System.IO Imports System.Text Imports System.Security.AccessControl Module FileStreamExample Sub Main() Try ' Create a file and write data to it. ' Create an array of bytes. Dim messageByte As Byte() = Encoding.ASCII.GetBytes("Here is some data.") ' Specify an access control list (ACL) Dim fs As New FileSecurity() fs.AddAccessRule(New FileSystemAccessRule("DOMAINNAME\AccountName", FileSystemRights.ReadData, AccessControlType.Allow)) ' Create a file using the FileStream class. Dim fWrite As New FileStream("test.txt", FileMode.Create, FileSystemRights.Modify, FileShare.None, 8, FileOptions.None, fs) ' Write the number of bytes to the file. fWrite.WriteByte(System.Convert.ToByte(messageByte.Length)) ' Write the bytes to the file. fWrite.Write(messageByte, 0, messageByte.Length) ' Close the stream. fWrite.Close() ' Open a file and read the number of bytes. Dim fRead As New FileStream("test.txt", FileMode.Open) ' The first byte is the string length. Dim length As Integer = Fix(fRead.ReadByte()) ' Create a new byte array for the data. Dim readBytes(length) As Byte ' Read the data from the file. fRead.Read(readBytes, 0, readBytes.Length) ' Close the stream. fRead.Close() ' Display the data. Console.WriteLine(Encoding.ASCII.GetString(readBytes)) Console.WriteLine("Done writing and reading data.") Catch e As Exception Console.WriteLine(e) End Try Console.ReadLine() End Sub End Module
using System; using System.IO; using System.Text; using System.Security.AccessControl; namespace FileSystemExample { class FileStreamExample { public static void Main() { try { // Create a file and write data to it. // Create an array of bytes. byte[] messageByte = Encoding.ASCII.GetBytes("Here is some data."); // Specify an access control list (ACL) FileSecurity fs = new FileSecurity(); fs.AddAccessRule(new FileSystemAccessRule(@"DOMAINNAME\AccountName" , FileSystemRights.ReadData , AccessControlType.Allow)); // Create a file using the FileStream class. FileStream fWrite = new FileStream("test.txt", FileMode.Create, FileSystemRights.Modify, FileShare.None, 8, FileOptions.None, fs); // Write the number of bytes to the file. fWrite.WriteByte((byte)messageByte.Length); // Write the bytes to the file. fWrite.Write(messageByte, 0, messageByte.Length); // Close the stream. fWrite.Close(); // Open a file and read the number of bytes. FileStream fRead = new FileStream("test.txt", FileMode.Open); // The first byte is the string length. int length = (int)fRead.ReadByte(); // Create a new byte array for the data. byte[] readBytes = new byte[length]; // Read the data from the file. fRead.Read(readBytes, 0, readBytes.Length); // Close the stream. fRead.Close(); // Display the data. Console.WriteLine(Encoding.ASCII.GetString(readBytes)); Console.WriteLine("Done writing and reading data."); } catch (Exception e) { Console.WriteLine(e); } Console.ReadLine(); } } }
using namespace System; using namespace System::IO; using namespace System::Text; using namespace System::Security::AccessControl; using namespace System::Security::Principal; int main() { try { // Create a file and write data to it. // Create an array of bytes. array<Byte>^ messageByte = Encoding::ASCII->GetBytes("Here is some data."); // Specify an access control list (ACL) FileSecurity^ fs = gcnew FileSecurity(); fs->AddAccessRule( gcnew FileSystemAccessRule("MYDOMAIN\\MyAccount", FileSystemRights::Modify, AccessControlType::Allow)); // Create a file using the FileStream class. FileStream^ fWrite = gcnew FileStream("test.txt", FileMode::Create, FileSystemRights::Modify, FileShare::None, 8, FileOptions::None, fs); // Write the number of bytes to the file. fWrite->WriteByte((Byte)messageByte->Length); // Write the bytes to the file. fWrite->Write(messageByte, 0, messageByte->Length); // Close the stream. fWrite->Close(); // Open a file and read the number of bytes. FileStream^ fRead = gcnew FileStream("test.txt", FileMode::Open); // The first byte is the string length. int length = (int)fRead->ReadByte(); // Create a new byte array for the data. array<Byte>^ readBytes = gcnew array<Byte>(length); // Read the data from the file. fRead->Read(readBytes, 0, readBytes->Length); // Close the stream. fRead->Close(); // Display the data. Console::WriteLine(Encoding::ASCII->GetString(readBytes)); Console::WriteLine("Done writing and reading data."); } catch (IdentityNotMappedException^) { Console::WriteLine("You need to use your own credentials " + " 'MYDOMAIN\\MyAccount'."); } catch (IOException^ ex) { Console::WriteLine(ex->Message); } }


Windows 98, Windows 2000 SP4, Windows Millennium Edition, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition
開発プラットフォームの中には、.NET Framework によってサポートされていないバージョンがあります。サポートされているバージョンについては、「システム要件」を参照してください。


FileStream コンストラクタ


FileStream コンストラクタ (SafeFileHandle, FileAccess, Int32, Boolean)
アセンブリ: mscorlib (mscorlib.dll 内)

Public Sub New ( _ handle As SafeFileHandle, _ access As FileAccess, _ bufferSize As Integer, _ isAsync As Boolean _ )
Dim handle As SafeFileHandle Dim access As FileAccess Dim bufferSize As Integer Dim isAsync As Boolean Dim instance As New FileStream(handle, access, bufferSize, isAsync)
public function FileStream ( handle : SafeFileHandle, access : FileAccess, bufferSize : int, isAsync : boolean )


FileStream は、ハンドルを排他的に制御していると見なされます。FileStream がハンドルも保持しているときに、読み取り、書き込み、またはシークを実行すると、データが破損することがあります。データを保護するために、ハンドルを使用する前に Flush を呼び出し、ハンドルの使用後は Close 以外のメソッドを呼び出さないようにします。または、この FileStream コンストラクタを呼び出す前に、ハンドルに対して読み取りと書き込みを行います。
FileShare パラメータを指定しないタイプの FileStream コンストラクタに対しては、FileShare.Read が既定値です。
![]() |
---|
特定のカルチャ設定で文字セットをコンパイルし、同じ文字を異なるカルチャ設定で取得すると、文字が正しく解釈されない場合があり、例外がスローされることもあります。 |
その他の一般的な 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 |


Windows 98, Windows 2000 SP4, Windows Millennium Edition, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition
開発プラットフォームの中には、.NET Framework によってサポートされていないバージョンがあります。サポートされているバージョンについては、「システム要件」を参照してください。


FileStream コンストラクタ (String, FileMode, FileAccess)
アセンブリ: mscorlib (mscorlib.dll 内)

Dim path As String Dim mode As FileMode Dim access As FileAccess Dim instance As New FileStream(path, mode, access)

例外の種類 | 条件 |
---|---|
ArgumentNullException | path が null 参照 (Visual Basic では Nothing) です。 |
ArgumentException | path が空の文字列 ("") か、空白しか含んでいないか、無効な文字を 1 つ以上含んでいます。 または path がファイル以外のデバイスを参照しています (NTFS 環境の "con:"、"com1:"、"lpt1:" など)。 |
NotSupportedException | path がファイル以外のデバイスを参照しています (NTFS 以外の環境の "con:"、"com1:"、"lpt1:" など)。 |
ArgumentException | |
FileNotFoundException | ファイルが見つかりません。たとえば、mode が FileMode.Truncate または FileMode.Open の場合に、path で指定されたファイルが存在しません。これらのモードでは、ファイルが既に存在している必要があります。 |
IOException | FileMode.CreateNew が指定されているのに、path で指定したファイルが既に存在していることなどが原因で I/O エラーが発生しました。 または |
SecurityException | |
DirectoryNotFoundException | |
UnauthorizedAccessException | access が Write または ReadWrite であるのに、ファイルまたはディレクトリが読み取り専用に設定されているなど、指定した path に対する access 要求がオペレーティング システムで許可されません。 |
PathTooLongException | 指定したパス、ファイル名、またはその両方がシステム定義の最大長を超えています。たとえば、Windows ベースのプラットフォームの場合、パスの長さは 248 文字未満、ファイル名の長さは 260 文字未満である必要があります。 |
ArgumentOutOfRangeException |

.NET Framework では、"\\.\PHYSICALDRIVE0" など、デバイス名を指定したパスを使用して物理ディスクに直接アクセスすることはできません。
path パラメータにはファイル名も指定できます。このファイルには、UNC 共有のファイルも含まれます。
コンストラクタにはファイルへの読み取り/書き込みアクセス権が付与されます。ファイルは共有読み取りモードで開きます。そのため、FileStream オブジェクトが閉じられるまで、この処理または別の処理でファイルを書き込み用に開く要求は失敗しますが、読み取り要求は成功します。バッファ サイズは、既定のサイズである 8192 バイト (8 KB) に設定されます。
![]() |
---|
特定のカルチャ設定で文字セットをコンパイルし、同じ文字を異なるカルチャ設定で取得すると、文字が正しく解釈されない場合があり、例外がスローされることもあります。 |
その他の一般的な 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 |


Windows 98, Windows 2000 SP4, Windows Millennium Edition, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition
開発プラットフォームの中には、.NET Framework によってサポートされていないバージョンがあります。サポートされているバージョンについては、「システム要件」を参照してください。


FileStream コンストラクタ (IntPtr, FileAccess, Boolean, Int32)
メモ : このコンストラクタは、互換性のために残されています。
FileStream クラスの新しいインスタンスを、指定した読み取り/書き込みアクセス許可、FileStream インスタンスの所有権、およびバッファ サイズを使用して、指定したファイル ハンドル用に初期化します。 名前空間: System.IOアセンブリ: mscorlib (mscorlib.dll 内)

<ObsoleteAttribute("This constructor has been deprecated. Please use new FileStream(SafeFileHandle handle, FileAccess access, int bufferSize) instead, and optionally make a new SafeFileHandle with ownsHandle=false if needed. http://go.microsoft.com/fwlink/?linkid=14202")> _ Public Sub New ( _ handle As IntPtr, _ access As FileAccess, _ ownsHandle As Boolean, _ bufferSize As Integer _ )
Dim handle As IntPtr Dim access As FileAccess Dim ownsHandle As Boolean Dim bufferSize As Integer Dim instance As New FileStream(handle, access, ownsHandle, bufferSize)
[ObsoleteAttribute("This constructor has been deprecated. Please use new FileStream(SafeFileHandle handle, FileAccess access, int bufferSize) instead, and optionally make a new SafeFileHandle with ownsHandle=false if needed. http://go.microsoft.com/fwlink/?linkid=14202")] public FileStream ( IntPtr handle, FileAccess access, bool ownsHandle, int bufferSize )
[ObsoleteAttribute(L"This constructor has been deprecated. Please use new FileStream(SafeFileHandle handle, FileAccess access, int bufferSize) instead, and optionally make a new SafeFileHandle with ownsHandle=false if needed. http://go.microsoft.com/fwlink/?linkid=14202")] public: FileStream ( IntPtr handle, FileAccess access, bool ownsHandle, int bufferSize )
/** @attribute ObsoleteAttribute("This constructor has been deprecated. Please use new FileStream(SafeFileHandle handle, FileAccess access, int bufferSize) instead, and optionally make a new SafeFileHandle with ownsHandle=false if needed. http://go.microsoft.com/fwlink/?linkid=14202") */ public FileStream ( IntPtr handle, FileAccess access, boolean ownsHandle, int bufferSize )
ObsoleteAttribute("This constructor has been deprecated. Please use new FileStream(SafeFileHandle handle, FileAccess access, int bufferSize) instead, and optionally make a new SafeFileHandle with ownsHandle=false if needed. http://go.microsoft.com/fwlink/?linkid=14202") public function FileStream ( handle : IntPtr, access : FileAccess, ownsHandle : boolean, bufferSize : int )


FileStream オブジェクトには、ファイルへの指定したアクセス権が付与されます。ハンドルの所有権は、指定されているとおりになります。この FileStream がハンドルを所有している場合は、Close メソッドの呼び出しによって、ハンドルも閉じられます。特に、そのファイルのハンドル カウントがデクリメントされます。FileStream オブジェクトには、指定したバッファ サイズが付与されます。
FileStream は、ハンドルを排他的に制御していると見なされます。FileStream がハンドルも保持しているときに、読み取り、書き込み、またはシークを実行すると、データが破損することがあります。データを保護するために、ハンドルを使用する前に Flush を呼び出し、ハンドルの使用後は Close 以外のメソッドを呼び出さないようにします。または、この FileStream コンストラクタを呼び出す前に、ハンドルに対して読み取りと書き込みを行います。
FileShare パラメータを指定しないタイプの FileStream コンストラクタに対しては、FileShare.Read が既定値です。
![]() |
---|
特定のカルチャ設定で文字セットをコンパイルし、同じ文字を異なるカルチャ設定で取得すると、文字が正しく解釈されない場合があり、例外がスローされることもあります。 |
その他の一般的な 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 |


Windows 98, Windows 2000 SP4, Windows Millennium Edition, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition
開発プラットフォームの中には、.NET Framework によってサポートされていないバージョンがあります。サポートされているバージョンについては、「システム要件」を参照してください。


FileStream コンストラクタ (IntPtr, FileAccess, Boolean)
メモ : このコンストラクタは、互換性のために残されています。
FileStream クラスの新しいインスタンスを、指定した読み取り/書き込みアクセス許可と FileStream インスタンスの所有権を使用して、指定したファイル ハンドル用に初期化します。 名前空間: System.IOアセンブリ: mscorlib (mscorlib.dll 内)

<ObsoleteAttribute("This constructor has been deprecated. Please use new FileStream(SafeFileHandle handle, FileAccess access) instead, and optionally make a new SafeFileHandle with ownsHandle=false if needed. http://go.microsoft.com/fwlink/?linkid=14202")> _ Public Sub New ( _ handle As IntPtr, _ access As FileAccess, _ ownsHandle As Boolean _ )
Dim handle As IntPtr Dim access As FileAccess Dim ownsHandle As Boolean Dim instance As New FileStream(handle, access, ownsHandle)
[ObsoleteAttribute("This constructor has been deprecated. Please use new FileStream(SafeFileHandle handle, FileAccess access) instead, and optionally make a new SafeFileHandle with ownsHandle=false if needed. http://go.microsoft.com/fwlink/?linkid=14202")] public FileStream ( IntPtr handle, FileAccess access, bool ownsHandle )
[ObsoleteAttribute(L"This constructor has been deprecated. Please use new FileStream(SafeFileHandle handle, FileAccess access) instead, and optionally make a new SafeFileHandle with ownsHandle=false if needed. http://go.microsoft.com/fwlink/?linkid=14202")] public: FileStream ( IntPtr handle, FileAccess access, bool ownsHandle )
/** @attribute ObsoleteAttribute("This constructor has been deprecated. Please use new FileStream(SafeFileHandle handle, FileAccess access) instead, and optionally make a new SafeFileHandle with ownsHandle=false if needed. http://go.microsoft.com/fwlink/?linkid=14202") */ public FileStream ( IntPtr handle, FileAccess access, boolean ownsHandle )
ObsoleteAttribute("This constructor has been deprecated. Please use new FileStream(SafeFileHandle handle, FileAccess access) instead, and optionally make a new SafeFileHandle with ownsHandle=false if needed. http://go.microsoft.com/fwlink/?linkid=14202") public function FileStream ( handle : IntPtr, access : FileAccess, ownsHandle : boolean )


FileStream オブジェクトには、ファイルへの指定したアクセス権が付与されます。ハンドルの所有権は、指定されているとおりになります。このプロセスがハンドルを所有している場合は、Close メソッドの呼び出しによって、ハンドルも閉じられ、ファイルのハンドル カウントがデクリメントされます。FileStream オブジェクトには、8,192 バイトの既定のバッファ サイズが付与されます。
FileStream は、ハンドルを排他的に制御していると見なされます。FileStream がハンドルも保持しているときに、読み取り、書き込み、またはシークを実行すると、データが破損することがあります。データを保護するために、ハンドルを使用する前に Flush を呼び出し、ハンドルの使用後は Close 以外のメソッドを呼び出さないようにします。
FileShare パラメータを指定しないタイプの FileStream コンストラクタに対しては、FileShare.Read が既定値です。
![]() |
---|
特定のカルチャ設定で文字セットをコンパイルし、同じ文字を異なるカルチャ設定で取得すると、文字が正しく解釈されない場合があり、例外がスローされることもあります。 |
その他の一般的な 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 |


Windows 98, Windows 2000 SP4, Windows Millennium Edition, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition
開発プラットフォームの中には、.NET Framework によってサポートされていないバージョンがあります。サポートされているバージョンについては、「システム要件」を参照してください。


FileStream コンストラクタ (SafeFileHandle, FileAccess, Int32)
アセンブリ: mscorlib (mscorlib.dll 内)

Dim handle As SafeFileHandle Dim access As FileAccess Dim bufferSize As Integer Dim instance As New FileStream(handle, access, bufferSize)


FileStream は、ハンドルを排他的に制御していると見なされます。FileStream がハンドルも保持しているときに、読み取り、書き込み、またはシークを実行すると、データが破損することがあります。データを保護するために、ハンドルを使用する前に Flush を呼び出し、ハンドルの使用後は Close 以外のメソッドを呼び出さないようにします。または、この FileStream コンストラクタを呼び出す前に、ハンドルに対して読み取りと書き込みを行います。
FileShare パラメータを指定しないタイプの FileStream コンストラクタに対しては、FileShare.Read が既定値です。
![]() |
---|
特定のカルチャ設定で文字セットをコンパイルし、同じ文字を異なるカルチャ設定で取得すると、文字が正しく解釈されない場合があり、例外がスローされることもあります。 |
その他の一般的な 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 |


Windows 98, Windows 2000 SP4, Windows Millennium Edition, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition
開発プラットフォームの中には、.NET Framework によってサポートされていないバージョンがあります。サポートされているバージョンについては、「システム要件」を参照してください。


FileStream コンストラクタ (String, FileMode)
アセンブリ: mscorlib (mscorlib.dll 内)


例外の種類 | 条件 |
---|---|
ArgumentException | path が空の文字列 ("") か、空白しか含んでいないか、無効な文字を 1 つ以上含んでいます。 または path がファイル以外のデバイスを参照しています (NTFS 環境の "con:"、"com1:"、"lpt1:" など)。 |
NotSupportedException | path がファイル以外のデバイスを参照しています (NTFS 以外の環境の "con:"、"com1:"、"lpt1:" など)。 |
ArgumentNullException | path が null 参照 (Visual Basic では Nothing) です。 |
SecurityException | |
FileNotFoundException | ファイルが見つかりません。たとえば、mode が FileMode.Truncate または FileMode.Open の場合に、path で指定されたファイルが存在しません。これらのモードでは、ファイルが既に存在している必要があります。 |
IOException | FileMode.CreateNew が指定されているのに、path で指定したファイルが既に存在していることなどが原因で I/O エラーが発生しました。 または |
DirectoryNotFoundException | |
PathTooLongException | 指定したパス、ファイル名、またはその両方がシステム定義の最大長を超えています。たとえば、Windows ベースのプラットフォームの場合、パスの長さは 248 文字未満、ファイル名の長さは 260 文字未満である必要があります。 |
ArgumentOutOfRangeException |

.NET Framework では、"\\.\PHYSICALDRIVE0" など、デバイス名を指定したパスを使用して物理ディスクに直接アクセスすることはできません。
path パラメータにはファイル名も指定できます。このファイルには、UNC 共有のファイルも含まれます。
コンストラクタにはファイルへの読み取り/書き込みアクセス権が付与されます。ファイルは共有読み取りモードで開きます。そのため、FileStream オブジェクトが閉じられるまで、この処理または別の処理でファイルを書き込み用に開く要求は失敗しますが、読み取り要求は成功します。バッファ サイズは、既定のサイズである 4096 バイト (4 KB) に設定されます。
![]() |
---|
特定のカルチャ設定で文字セットをコンパイルし、同じ文字を異なるカルチャ設定で取得すると、文字が正しく解釈されない場合があり、例外がスローされることもあります。 |
その他の一般的な 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 |

ファイルにデータをバイト単位で書き込み、さらにデータが正常に書き込まれたことを確認する例を次に示します。
Imports Microsoft.VisualBasic Imports System Imports System.IO Imports System.Text Class FStream Shared Sub Main() Const fileName As String = "Test#@@#.dat" ' Create random data to write to the file. Dim dataArray(100000) As Byte Dim randomGenerator As New Random() randomGenerator.NextBytes(dataArray) Dim fileStream As FileStream = _ new FileStream(fileName, FileMode.Create) Try ' Write the data to the file, byte by byte. For i As Integer = 0 To dataArray.Length - 1 fileStream.WriteByte(dataArray(i)) Next i ' Set the stream position to the beginning of the stream. fileStream.Seek(0, SeekOrigin.Begin) ' Read and verify the data. For i As Integer = 0 To _ CType(fileStream.Length, Integer) - 1 If dataArray(i) <> fileStream.ReadByte() Then Console.WriteLine("Error writing data.") Return End If Next i Console.WriteLine("The data was written to {0} " & _ "and verified.", fileStream.Name) Finally fileStream.Close() End Try End Sub End Class
using System; using System.IO; class FStream { static void Main() { const string fileName = "Test#@@#.dat"; // Create random data to write to the file. byte[] dataArray = new byte[100000]; new Random().NextBytes(dataArray); using(FileStream fileStream = new FileStream(fileName, FileMode.Create)) { // Write the data to the file, byte by byte. for(int i = 0; i < dataArray.Length; i++) { fileStream.WriteByte(dataArray[i]); } // Set the stream position to the beginning of the file. fileStream.Seek(0, SeekOrigin.Begin); // Read and verify the data. for(int i = 0; i < fileStream.Length; i++) { if(dataArray[i] != fileStream.ReadByte()) { Console.WriteLine("Error writing data."); return; } } Console.WriteLine("The data was written to {0} " + "and verified.", fileStream.Name); } } }
using namespace System; using namespace System::IO; int main() { String^ fileName = "Test@##@.dat"; // Create random data to write to the file. array<Byte>^dataArray = gcnew array<Byte>(100000); (gcnew Random)->NextBytes( dataArray ); FileStream^ fileStream = gcnew FileStream( fileName,FileMode::Create ); try { // Write the data to the file, byte by byte. for ( int i = 0; i < dataArray->Length; i++ ) { fileStream->WriteByte( dataArray[ i ] ); } // Set the stream position to the beginning of the file. fileStream->Seek( 0, SeekOrigin::Begin ); // Read and verify the data. for ( int i = 0; i < fileStream->Length; i++ ) { if ( dataArray[ i ] != fileStream->ReadByte() ) { Console::WriteLine( "Error writing data." ); return -1; } } Console::WriteLine( "The data was written to {0} " "and verified.", fileStream->Name ); } finally { fileStream->Close(); } }
import System.*; import System.IO.*; class FStream { public static void main(String[] args) { final String fileName = "Test#@@#.dat"; // Create random data to write to the file. ubyte dataArray[] = new ubyte[100000]; new Random().NextBytes(dataArray); FileStream fileStream = new FileStream(fileName, FileMode.Create); try { // Write the data to the file, byte by byte. for(int i=0;i < dataArray.length;i++) { fileStream.WriteByte(dataArray[i]); } // Set the stream position to the beginning of the file. fileStream.Seek(0, SeekOrigin.Begin); // Read and verify the data. for(int i=0;i < fileStream.get_Length();i++) { if ( dataArray[i] != fileStream.ReadByte() ) { Console.WriteLine("Error writing data."); return; } } Console.WriteLine("The data was written to {0} " + "and verified.", fileStream.get_Name()); } finally { fileStream.Dispose(); } } //main } //FStream


Windows 98, Windows 2000 SP4, Windows Millennium Edition, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition
開発プラットフォームの中には、.NET Framework によってサポートされていないバージョンがあります。サポートされているバージョンについては、「システム要件」を参照してください。


FileStream コンストラクタ (String, FileMode, FileAccess, FileShare)
アセンブリ: mscorlib (mscorlib.dll 内)

Public Sub New ( _ path As String, _ mode As FileMode, _ access As FileAccess, _ share As FileShare _ )
Dim path As String Dim mode As FileMode Dim access As FileAccess Dim share As FileShare Dim instance As New FileStream(path, mode, access, share)
public function FileStream ( path : String, mode : FileMode, access : FileAccess, share : FileShare )

例外の種類 | 条件 |
---|---|
ArgumentNullException | path が null 参照 (Visual Basic では Nothing) です。 |
ArgumentException | path が空の文字列 ("") か、空白しか含んでいないか、無効な文字を 1 つ以上含んでいます。 または path がファイル以外のデバイスを参照しています (NTFS 環境の "con:"、"com1:"、"lpt1:" など)。 |
NotSupportedException | path がファイル以外のデバイスを参照しています (NTFS 以外の環境の "con:"、"com1:"、"lpt1:" など)。 |
ArgumentException | |
FileNotFoundException | ファイルが見つかりません。たとえば、mode が FileMode.Truncate または FileMode.Open の場合に、path で指定されたファイルが存在しません。これらのモードでは、ファイルが既に存在している必要があります。 |
IOException | FileMode.CreateNew が指定されているのに、path で指定したファイルが既に存在していることなどが原因で I/O エラーが発生しました。 または システムで Windows 98 または Windows 98 Second Edition を実行しており、share が FileShare.Delete に設定されています。 または |
SecurityException | |
DirectoryNotFoundException | |
UnauthorizedAccessException | access が Write または ReadWrite であるのに、ファイルまたはディレクトリが読み取り専用に設定されているなど、指定した path に対する access 要求がオペレーティング システムで許可されません。 |
PathTooLongException | 指定したパス、ファイル名、またはその両方がシステム定義の最大長を超えています。たとえば、Windows ベースのプラットフォームの場合、パスの長さは 248 文字未満、ファイル名の長さは 260 文字未満である必要があります。 |
ArgumentOutOfRangeException |

.NET Framework では、"\\.\PHYSICALDRIVE0" など、デバイス名を指定したパスを使用して物理ディスクに直接アクセスすることはできません。
path パラメータにはファイル名も指定できます。このファイルには、UNC 共有のファイルも含まれます。
コンストラクタにはファイルへの読み取り/書き込みアクセス権が付与されます。ファイルは共有読み取りモードで開きます。そのため、FileStream オブジェクトが閉じられるまで、この処理または別の処理でファイルを書き込み用に開く要求は失敗しますが、読み取り要求は成功します。バッファ サイズは、既定のサイズである 8192 バイト (8 KB) に設定されます。
![]() |
---|
特定のカルチャ設定で文字セットをコンパイルし、同じ文字を異なるカルチャ設定で取得すると、文字が正しく解釈されない場合があり、例外がスローされることもあります。 |
その他の一般的な 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 |

Dim aFileStream As New FileStream( _ "Test#@@#.dat", FileMode.OpenOrCreate, _ FileAccess.ReadWrite, FileShare.ReadWrite)
using(FileStream fileStream = new FileStream( "Test#@@#.dat", FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite))
FileStream^ fileStream = gcnew FileStream( "Test#@@#.dat",FileMode::OpenOrCreate,FileAccess::ReadWrite,FileShare::ReadWrite );


Windows 98, Windows 2000 SP4, Windows Millennium Edition, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition
開発プラットフォームの中には、.NET Framework によってサポートされていないバージョンがあります。サポートされているバージョンについては、「システム要件」を参照してください。


FileStream コンストラクタ (String, FileMode, FileAccess, FileShare, Int32, Boolean)
アセンブリ: mscorlib (mscorlib.dll 内)

Public Sub New ( _ path As String, _ mode As FileMode, _ access As FileAccess, _ share As FileShare, _ bufferSize As Integer, _ useAsync As Boolean _ )
Dim path As String Dim mode As FileMode Dim access As FileAccess Dim share As FileShare Dim bufferSize As Integer Dim useAsync As Boolean Dim instance As New FileStream(path, mode, access, share, bufferSize, useAsync)
public FileStream ( string path, FileMode mode, FileAccess access, FileShare share, int bufferSize, bool useAsync )
public: FileStream ( String^ path, FileMode mode, FileAccess access, FileShare share, int bufferSize, bool useAsync )
public FileStream ( String path, FileMode mode, FileAccess access, FileShare share, int bufferSize, boolean useAsync )
public function FileStream ( path : String, mode : FileMode, access : FileAccess, share : FileShare, bufferSize : int, useAsync : boolean )
- access
FileStream オブジェクトがファイルにアクセスする方法を決定する FileAccess 定数。これは、FileStream オブジェクトの CanRead プロパティと CanWrite プロパティを取得します。path にディスク ファイルが指定されている場合、CanSeek は true になります。
- useAsync
非同期 I/O または同期 I/O のどちらを使用するかを指定します。ただし、基になるオペレーティング システムが非同期 I/O をサポートしていないことがあります。したがって、true を指定しても、プラットフォームによってはハンドルが同期的に開かれることがあります。非同期的に開いた場合、BeginRead メソッドと BeginWrite メソッドは、大量の読み取りまたは書き込み時にはパフォーマンスがより高くなりますが、少量の読み取りまたは書き込み時にはパフォーマンスが非常に低くなることがあります。アプリケーションが非同期 I/O を利用するように設計されている場合は、useAsync パラメータを true に設定します。非同期 I/O を正しく使用すると、アプリケーションが 10 倍ほど高速化することがあります。ただし、非同期 I/O 用にアプリケーションを再設計せずに非同期 I/O を使用すると、パフォーマンスが 10 分の 1 ほど低下することがあります。

例外の種類 | 条件 |
---|---|
ArgumentNullException | path が null 参照 (Visual Basic では Nothing) です。 |
ArgumentException | path が空の文字列 ("") か、空白しか含んでいないか、無効な文字を 1 つ以上含んでいます。 または path がファイル以外のデバイスを参照しています (NTFS 環境の "con:"、"com1:"、"lpt1:" など)。 |
NotSupportedException | path がファイル以外のデバイスを参照しています (NTFS 以外の環境の "con:"、"com1:"、"lpt1:" など)。 |
ArgumentException | |
ArgumentOutOfRangeException | bufferSize が負の値またはゼロです。 または |
FileNotFoundException | ファイルが見つかりません。たとえば、mode が FileMode.Truncate または FileMode.Open の場合に、path で指定されたファイルが存在しません。これらのモードでは、ファイルが既に存在している必要があります。 |
IOException | FileMode.CreateNew が指定されているのに、path で指定したファイルが既に存在していることなどが原因で I/O エラーが発生しました。 または システムで Windows 98 または Windows 98 Second Edition を実行しており、share が FileShare.Delete に設定されています。 または |
SecurityException | |
DirectoryNotFoundException | |
UnauthorizedAccessException | access が Write または ReadWrite であるのに、ファイルまたはディレクトリが読み取り専用に設定されているなど、指定した path に対する access 要求がオペレーティング システムで許可されません。 |
PathTooLongException | 指定したパス、ファイル名、またはその両方がシステム定義の最大長を超えています。たとえば、Windows ベースのプラットフォームの場合、パスの長さは 248 文字未満、ファイル名の長さは 260 文字未満である必要があります。 |

.NET Framework では、"\\.\PHYSICALDRIVE0" など、デバイス名を指定したパスを使用して物理ディスクに直接アクセスすることはできません。
path パラメータにはファイル名も指定できます。このファイルには、UNC 共有のファイルも含まれます。
![]() |
---|
特定のカルチャ設定で文字セットをコンパイルし、同じ文字を異なるカルチャ設定で取得すると、文字が正しく解釈されない場合があり、例外がスローされることもあります。 |
その他の一般的な 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 |

ファイルにデータを非同期的に書き込み、さらにデータが正常に書き込まれたことを確認する例を次に示します。EndReadCallback メソッドと EndWriteCallback メソッドにメイン スレッドの情報を渡すために、State オブジェクトが作成されます。
Imports System Imports System.IO Imports System.Threading Class FStream Shared Sub Main() ' Create a synchronization object that gets ' signaled when verification is complete. Dim manualEvent As New ManualResetEvent(False) ' Create random data to write to the file. Dim writeArray(100000) As Byte Dim randomGenerator As New Random() randomGenerator.NextBytes(writeArray) Dim fStream As New FileStream("Test#@@#.dat", _ FileMode.Create, FileAccess.ReadWrite, _ FileShare.None, 4096, True) ' Check that the FileStream was opened asynchronously. If fStream.IsAsync = True Console.WriteLine("fStream was opened asynchronously.") Else Console.WriteLine("fStream was not opened asynchronously.") End If ' Asynchronously write to the file. Dim asyncResult As IAsyncResult = fStream.BeginWrite( _ writeArray, 0, writeArray.Length, _ AddressOf EndWriteCallback , _ New State(fStream, writeArray, manualEvent)) ' Concurrently do other work and then wait ' for the data to be written and verified. manualEvent.WaitOne(5000, False) End Sub ' When BeginWrite is finished writing data to the file, the ' EndWriteCallback method is called to end the asynchronous ' write operation and then read back and verify the data. Private Shared Sub EndWriteCallback(asyncResult As IAsyncResult) Dim tempState As State = _ DirectCast(asyncResult.AsyncState, State) Dim fStream As FileStream = tempState.FStream fStream.EndWrite(asyncResult) ' Asynchronously read back the written data. fStream.Position = 0 asyncResult = fStream.BeginRead( _ tempState.ReadArray, 0 , tempState.ReadArray.Length, _ AddressOf EndReadCallback, tempState) ' Concurrently do other work, such as ' logging the write operation. End Sub ' When BeginRead is finished reading data from the file, the ' EndReadCallback method is called to end the asynchronous ' read operation and then verify the data. Private Shared Sub EndReadCallback(asyncResult As IAsyncResult) Dim tempState As State = _ DirectCast(asyncResult.AsyncState, State) Dim readCount As Integer = _ tempState.FStream.EndRead(asyncResult) Dim i As Integer = 0 While(i < readCount) If(tempState.ReadArray(i) <> tempState.WriteArray(i)) Console.WriteLine("Error writing data.") tempState.FStream.Close() Return End If i += 1 End While Console.WriteLine("The data was written to {0} and " & _ "verified.", tempState.FStream.Name) tempState.FStream.Close() ' Signal the main thread that the verification is finished. tempState.ManualEvent.Set() End Sub ' Maintain state information to be passed to ' EndWriteCallback and EndReadCallback. Private Class State ' fStreamValue is used to read and write to the file. Dim fStreamValue As FileStream ' writeArrayValue stores data that is written to the file. Dim writeArrayValue As Byte() ' readArrayValue stores data that is read from the file. Dim readArrayValue As Byte() ' manualEvent signals the main thread ' when verification is complete. Dim manualEventValue As ManualResetEvent Sub New(aStream As FileStream, anArray As Byte(), _ manualEvent As ManualResetEvent) fStreamValue = aStream writeArrayValue = anArray manualEventValue = manualEvent readArrayValue = New Byte(anArray.Length - 1){} End Sub Public ReadOnly Property FStream() As FileStream Get Return fStreamValue End Get End Property Public ReadOnly Property WriteArray() As Byte() Get Return writeArrayValue End Get End Property Public ReadOnly Property ReadArray() As Byte() Get Return readArrayValue End Get End Property Public ReadOnly Property ManualEvent() As ManualResetEvent Get Return manualEventValue End Get End Property End Class End Class
using System; using System.IO; using System.Threading; class FStream { static void Main() { // Create a synchronization object that gets // signaled when verification is complete. ManualResetEvent manualEvent = new ManualResetEvent(false); // Create random data to write to the file. byte[] writeArray = new byte[100000]; new Random().NextBytes(writeArray); FileStream fStream = new FileStream("Test#@@#.dat", FileMode.Create, FileAccess.ReadWrite, FileShare.None, 4096, true); // Check that the FileStream was opened asynchronously. Console.WriteLine("fStream was {0}opened asynchronously.", fStream.IsAsync ? "" : "not "); // Asynchronously write to the file. IAsyncResult asyncResult = fStream.BeginWrite( writeArray, 0, writeArray.Length, new AsyncCallback(EndWriteCallback), new State(fStream, writeArray, manualEvent)); // Concurrently do other work and then wait // for the data to be written and verified. manualEvent.WaitOne(5000, false); } // When BeginWrite is finished writing data to the file, the // EndWriteCallback method is called to end the asynchronous // write operation and then read back and verify the data. static void EndWriteCallback(IAsyncResult asyncResult) { State tempState = (State)asyncResult.AsyncState; FileStream fStream = tempState.FStream; fStream.EndWrite(asyncResult); // Asynchronously read back the written data. fStream.Position = 0; asyncResult = fStream.BeginRead( tempState.ReadArray, 0 , tempState.ReadArray.Length, new AsyncCallback(EndReadCallback), tempState); // Concurrently do other work, such as // logging the write operation. } // When BeginRead is finished reading data from the file, the // EndReadCallback method is called to end the asynchronous // read operation and then verify the data. static void EndReadCallback(IAsyncResult asyncResult) { State tempState = (State)asyncResult.AsyncState; int readCount = tempState.FStream.EndRead(asyncResult); int i = 0; while(i < readCount) { if(tempState.ReadArray[i] != tempState.WriteArray[i++]) { Console.WriteLine("Error writing data."); tempState.FStream.Close(); return; } } Console.WriteLine("The data was written to {0} and verified.", tempState.FStream.Name); tempState.FStream.Close(); // Signal the main thread that the verification is finished. tempState.ManualEvent.Set(); } // Maintain state information to be passed to // EndWriteCallback and EndReadCallback. class State { // fStream is used to read and write to the file. FileStream fStream; // writeArray stores data that is written to the file. byte[] writeArray; // readArray stores data that is read from the file. byte[] readArray; // manualEvent signals the main thread // when verification is complete. ManualResetEvent manualEvent; public State(FileStream fStream, byte[] writeArray, ManualResetEvent manualEvent) { this.fStream = fStream; this.writeArray = writeArray; this.manualEvent = manualEvent; readArray = new byte[writeArray.Length]; } public FileStream FStream { get{ return fStream; } } public byte[] WriteArray { get{ return writeArray; } } public byte[] ReadArray { get{ return readArray; } } public ManualResetEvent ManualEvent { get{ return manualEvent; } } } }
using namespace System; using namespace System::IO; using namespace System::Threading; // Maintain state information to be passed to // EndWriteCallback and EndReadCallback. ref class State { private: // fStream is used to read and write to the file. FileStream^ fStream; // writeArray stores data that is written to the file. array<Byte>^writeArray; // readArray stores data that is read from the file. array<Byte>^readArray; // manualEvent signals the main thread // when verification is complete. ManualResetEvent^ manualEvent; public: State( FileStream^ fStream, array<Byte>^writeArray, ManualResetEvent^ manualEvent ) { this->fStream = fStream; this->writeArray = writeArray; this->manualEvent = manualEvent; readArray = gcnew array<Byte>(writeArray->Length); } property FileStream^ FStream { FileStream^ get() { return fStream; } } property array<Byte>^ WriteArray { array<Byte>^ get() { return writeArray; } } property array<Byte>^ ReadArray { array<Byte>^ get() { return readArray; } } property ManualResetEvent^ ManualEvent { ManualResetEvent^ get() { return manualEvent; } } }; ref class FStream { private: // When BeginRead is finished reading data from the file, the // EndReadCallback method is called to end the asynchronous // read operation and then verify the data. static void EndReadCallback( IAsyncResult^ asyncResult ) { State^ tempState = dynamic_cast<State^>(asyncResult->AsyncState); int readCount = tempState->FStream->EndRead( asyncResult ); int i = 0; while ( i < readCount ) { if ( tempState->ReadArray[ i ] != tempState->WriteArray[ i++ ] ) { Console::WriteLine( "Error writing data." ); tempState->FStream->Close(); return; } } Console::WriteLine( "The data was written to {0} " "and verified.", tempState->FStream->Name ); tempState->FStream->Close(); // Signal the main thread that the verification is finished. tempState->ManualEvent->Set(); } public: // When BeginWrite is finished writing data to the file, the // EndWriteCallback method is called to end the asynchronous // write operation and then read back and verify the data. static void EndWriteCallback( IAsyncResult^ asyncResult ) { State^ tempState = dynamic_cast<State^>(asyncResult->AsyncState); FileStream^ fStream = tempState->FStream; fStream->EndWrite( asyncResult ); // Asynchronously read back the written data. fStream->Position = 0; asyncResult = fStream->BeginRead( tempState->ReadArray, 0, tempState->ReadArray->Length, gcnew AsyncCallback( &FStream::EndReadCallback ), tempState ); // Concurrently do other work, such as // logging the write operation. } }; int main() { // Create a synchronization object that gets // signaled when verification is complete. ManualResetEvent^ manualEvent = gcnew ManualResetEvent( false ); // Create the data to write to the file. array<Byte>^writeArray = gcnew array<Byte>(100000); (gcnew Random)->NextBytes( writeArray ); FileStream^ fStream = gcnew FileStream( "Test#@@#.dat",FileMode::Create,FileAccess::ReadWrite,FileShare::None,4096,true ); // Check that the FileStream was opened asynchronously. Console::WriteLine( "fStream was {0}opened asynchronously.", fStream->IsAsync ? (String^)"" : "not " ); // Asynchronously write to the file. IAsyncResult^ asyncResult = fStream->BeginWrite( writeArray, 0, writeArray->Length, gcnew AsyncCallback( &FStream::EndWriteCallback ), gcnew State( fStream,writeArray,manualEvent ) ); // Concurrently do other work and then wait // for the data to be written and verified. manualEvent->WaitOne( 5000, false ); }
import System.*; import System.IO.*; import System.Threading.*; class FStream { public static void main(String[] args) { // Create a synchronization object that gets // signaled when verification is complete. ManualResetEvent manualEvent = new ManualResetEvent(false); // Create random data to write to the file. ubyte writeArray[] = new ubyte[100000]; new Random().NextBytes(writeArray); FileStream fStream = new FileStream("Test#@@#.dat", FileMode.Create, FileAccess.ReadWrite, FileShare.None, 4096, true); // Check that the FileStream was opened asynchronously. Console.WriteLine("fStream was {0}opened asynchronously.", (fStream.get_IsAsync()) ? "" : "not "); FStream classfStream = new FStream(); // Asynchronously write to the file. IAsyncResult asyncResult = fStream.BeginWrite(writeArray, 0, writeArray.length, new AsyncCallback(EndWriteCallback) , classfStream.new State(fStream, writeArray, manualEvent)); // Concurrently do other work and then wait // for the data to be written and verified. manualEvent.WaitOne(5000, false); } //main // When BeginWrite is finished writing data to the file, the // EndWriteCallback method is called to end the asynchronous // write operation and then read back and verify the data. static void EndWriteCallback(IAsyncResult asyncResult) { State tempState = ((State)(asyncResult.get_AsyncState())); FileStream fStream = tempState.get_FStream(); fStream.EndWrite(asyncResult); // Asynchronously read back the written data. fStream.set_Position(0); asyncResult = fStream.BeginRead(tempState.get_ReadArray(), 0, tempState.get_ReadArray().length , new AsyncCallback(EndReadCallback), tempState); // Concurrently do other work, such as // logging the write operation. } //EndWriteCallback // When BeginRead is finished reading data from the file, the // EndReadCallback method is called to end the asynchronous // read operation and then verify the data. static void EndReadCallback(IAsyncResult asyncResult) { State tempState = ((State)(asyncResult.get_AsyncState())); int readCount = tempState.get_FStream().EndRead(asyncResult); int i = 0; while((i < readCount)) { if ( tempState.get_ReadArray()[i] != tempState.get_WriteArray()[i++] ) { Console.WriteLine("Error writing data."); tempState.get_FStream().Close(); return; } } Console.WriteLine("The data was written to {0} and verified.", tempState.get_FStream().get_Name()); tempState.get_FStream().Close(); // Signal the main thread that the verification is finished. tempState.get_ManualEvent().Set(); } //EndReadCallback // Maintain state information to be passed to // EndWriteCallback and EndReadCallback. class State { // fStream is used to read and write to the file. private FileStream fStream; // writeArray stores data that is written to the file. private ubyte writeArray[]; // readArray stores data that is read from the file. private ubyte readArray[]; // manualEvent signals the main thread // when verification is complete. private ManualResetEvent manualEvent; public State(FileStream fStream, ubyte writeArray[], ManualResetEvent manualEvent) { this.fStream = fStream; this.writeArray = writeArray; this.manualEvent = manualEvent; readArray = new ubyte[writeArray.length ]; } //State /** @property */ public FileStream get_FStream() { return fStream ; }//get_FStream /** @property */ public ubyte[] get_WriteArray() { return writeArray ; }//get_WriteArray /** @property */ public ubyte[] get_ReadArray() { return readArray; }//get_ReadArray /** @property */ public ManualResetEvent get_ManualEvent() { return manualEvent; }//get_ManualEvent } //State } //FStream


Windows 98, Windows 2000 SP4, Windows Millennium Edition, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition
開発プラットフォームの中には、.NET Framework によってサポートされていないバージョンがあります。サポートされているバージョンについては、「システム要件」を参照してください。


FileStream コンストラクタ (SafeFileHandle, FileAccess)
アセンブリ: mscorlib (mscorlib.dll 内)

Dim handle As SafeFileHandle Dim access As FileAccess Dim instance As New FileStream(handle, access)
public FileStream ( SafeFileHandle handle, FileAccess access )
public: FileStream ( SafeFileHandle^ handle, FileAccess access )
public FileStream ( SafeFileHandle handle, FileAccess access )


Close が呼び出されると、ハンドルも閉じられ、ファイルのハンドル カウントがデクリメントされます。
FileStream は、ハンドルを排他的に制御していると見なされます。FileStream がハンドルも保持しているときに、読み取り、書き込み、またはシークを実行すると、データが破損することがあります。データを保護するために、ハンドルを使用する前に Flush を呼び出し、ハンドルの使用後は Close 以外のメソッドを呼び出さないようにします。
![]() |
---|
特定のカルチャ設定で文字セットをコンパイルし、同じ文字を異なるカルチャ設定で取得すると、文字が正しく解釈されない場合があり、例外がスローされることもあります。 |
FileShare パラメータを指定しないタイプの FileStream コンストラクタに対しては、FileShare.Read が既定値です。
その他の一般的な 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 |


Windows 98, Windows 2000 SP4, Windows Millennium Edition, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition
開発プラットフォームの中には、.NET Framework によってサポートされていないバージョンがあります。サポートされているバージョンについては、「システム要件」を参照してください。


FileStream コンストラクタ (String, FileMode, FileAccess, FileShare, Int32, FileOptions)
アセンブリ: mscorlib (mscorlib.dll 内)

Public Sub New ( _ path As String, _ mode As FileMode, _ access As FileAccess, _ share As FileShare, _ bufferSize As Integer, _ options As FileOptions _ )
Dim path As String Dim mode As FileMode Dim access As FileAccess Dim share As FileShare Dim bufferSize As Integer Dim options As FileOptions Dim instance As New FileStream(path, mode, access, share, bufferSize, options)
public FileStream ( string path, FileMode mode, FileAccess access, FileShare share, int bufferSize, FileOptions options )
public: FileStream ( String^ path, FileMode mode, FileAccess access, FileShare share, int bufferSize, FileOptions options )
public FileStream ( String path, FileMode mode, FileAccess access, FileShare share, int bufferSize, FileOptions options )
public function FileStream ( path : String, mode : FileMode, access : FileAccess, share : FileShare, bufferSize : int, options : FileOptions )

例外の種類 | 条件 |
---|---|
ArgumentNullException | path が null 参照 (Visual Basic では Nothing) です。 |
ArgumentException | path が空の文字列 ("") か、空白しか含んでいないか、無効な文字を 1 つ以上含んでいます。 または path がファイル以外のデバイスを参照しています (NTFS 環境の "con:"、"com1:"、"lpt1:" など)。 |
NotSupportedException | path がファイル以外のデバイスを参照しています (NTFS 以外の環境の "con:"、"com1:"、"lpt1:" など)。 |
ArgumentException | |
ArgumentOutOfRangeException | bufferSize が負の値またはゼロです。 または |
FileNotFoundException | ファイルが見つかりません。たとえば、mode が FileMode.Truncate または FileMode.Open の場合に、path で指定されたファイルが存在しません。これらのモードでは、ファイルが既に存在している必要があります。 |
IOException | FileMode.CreateNew が指定されているのに、path で指定したファイルが既に存在していることなどが原因で I/O エラーが発生しました。 または |
SecurityException | |
DirectoryNotFoundException | |
UnauthorizedAccessException | access が Write または ReadWrite であるのに、ファイルまたはディレクトリが読み取り専用に設定されているなど、指定した path に対する access 要求がオペレーティング システムで許可されません。 |
PathTooLongException | 指定したパス、ファイル名、またはその両方がシステム定義の最大長を超えています。たとえば、Windows ベースのプラットフォームの場合、パスの長さは 248 文字未満、ファイル名の長さは 260 文字未満である必要があります。 |

.NET Framework では、"\\.\PHYSICALDRIVE0" など、デバイス名を指定したパスを使用して物理ディスクに直接アクセスすることはできません。
fileOptions パラメータを使用すると、FileStream オブジェクトの作成時に活用できる、より高度な操作を利用できます。
path パラメータにはファイル名も指定できます。このファイルには、UNC 共有のファイルも含まれます。
![]() |
---|
特定のカルチャ設定で文字セットをコンパイルし、同じ文字を異なるカルチャ設定で取得すると、文字が正しく解釈されない場合があり、例外がスローされることもあります。 |
その他の一般的な 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 オブジェクトを使用して、ファイルにデータを書き込み、次にデータを読み取る例を次に示します。
Imports System Imports System.IO Imports System.Text Imports System.Security.AccessControl Module FileStreamExample Sub Main() Try ' Create a file and write data to it. ' Create an array of bytes. Dim messageByte As Byte() = Encoding.ASCII.GetBytes("Here is some data.") ' Create a file using the FileStream class. Dim fWrite As New FileStream("test.txt", FileMode.Create, FileAccess.ReadWrite, FileShare.None, 8, FileOptions.None) ' Write the number of bytes to the file. fWrite.WriteByte(System.Convert.ToByte(messageByte.Length)) ' Write the bytes to the file. fWrite.Write(messageByte, 0, messageByte.Length) ' Close the stream. fWrite.Close() ' Open a file and read the number of bytes. Dim fRead As New FileStream("test.txt", FileMode.Open) ' The first byte is the string length. Dim length As Integer = Fix(fRead.ReadByte()) ' Create a new byte array for the data. Dim readBytes(length) As Byte ' Read the data from the file. fRead.Read(readBytes, 0, readBytes.Length) ' Close the stream. fRead.Close() ' Display the data. Console.WriteLine(Encoding.ASCII.GetString(readBytes)) Console.WriteLine("Done writing and reading data.") Catch e As Exception Console.WriteLine(e) End Try Console.ReadLine() End Sub End Module
using System; using System.IO; using System.Text; using System.Security.AccessControl; namespace FileSystemExample { class FileStreamExample { public static void Main() { try { // Create a file and write data to it. // Create an array of bytes. byte[] messageByte = Encoding.ASCII.GetBytes("Here is some data."); // Create a file using the FileStream class. FileStream fWrite = new FileStream("test.txt", FileMode.Create, FileAccess.ReadWrite, FileShare.None, 8, FileOptions.None); // Write the number of bytes to the file. fWrite.WriteByte((byte)messageByte.Length); // Write the bytes to the file. fWrite.Write(messageByte, 0, messageByte.Length); // Close the stream. fWrite.Close(); // Open a file and read the number of bytes. FileStream fRead = new FileStream("test.txt", FileMode.Open); // The first byte is the string length. int length = (int)fRead.ReadByte(); // Create a new byte array for the data. byte[] readBytes = new byte[length]; // Read the data from the file. fRead.Read(readBytes, 0, readBytes.Length); // Close the stream. fRead.Close(); // Display the data. Console.WriteLine(Encoding.ASCII.GetString(readBytes)); Console.WriteLine("Done writing and reading data."); } catch (Exception e) { Console.WriteLine(e); } Console.ReadLine(); } } }
#using <System.dll> using namespace System; using namespace System::IO; using namespace System::Text; using namespace System::Security::AccessControl; int main() { try { // Create a file and write data to it. // Create an array of bytes. array<Byte>^ messageByte = Encoding::ASCII->GetBytes("Here is some data."); // Create a file using the FileStream class. FileStream^ fWrite = gcnew FileStream("test.txt", FileMode::Create , FileAccess::ReadWrite, FileShare::None, 8, FileOptions::None); // Write the number of bytes to the file. fWrite->WriteByte((Byte)messageByte->Length); // Write the bytes to the file. fWrite->Write(messageByte, 0, messageByte->Length); // Close the stream. fWrite->Close(); // Open a file and read the number of bytes. FileStream^ fRead = gcnew FileStream("test.txt", FileMode::Open); // The first byte is the string length. int length = (int)fRead->ReadByte(); // Create a new byte array for the data. array<Byte>^ readBytes = gcnew array<Byte>(length); // Read the data from the file. fRead->Read(readBytes, 0, readBytes->Length); // Close the stream. fRead->Close(); // Display the data. Console::WriteLine(Encoding::ASCII->GetString(readBytes)); Console::WriteLine("Done writing and reading data."); } catch (IOException^ ex) { Console::WriteLine(ex->Message); } }


Windows 98, Windows 2000 SP4, Windows Millennium Edition, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition
開発プラットフォームの中には、.NET Framework によってサポートされていないバージョンがあります。サポートされているバージョンについては、「システム要件」を参照してください。


FileStream コンストラクタ (String, FileMode, FileAccess, FileShare, Int32)
アセンブリ: mscorlib (mscorlib.dll 内)

Public Sub New ( _ path As String, _ mode As FileMode, _ access As FileAccess, _ share As FileShare, _ bufferSize As Integer _ )
Dim path As String Dim mode As FileMode Dim access As FileAccess Dim share As FileShare Dim bufferSize As Integer Dim instance As New FileStream(path, mode, access, share, bufferSize)
public FileStream ( string path, FileMode mode, FileAccess access, FileShare share, int bufferSize )
public: FileStream ( String^ path, FileMode mode, FileAccess access, FileShare share, int bufferSize )
public FileStream ( String path, FileMode mode, FileAccess access, FileShare share, int bufferSize )
public function FileStream ( path : String, mode : FileMode, access : FileAccess, share : FileShare, bufferSize : int )

例外の種類 | 条件 |
---|---|
ArgumentNullException | path が null 参照 (Visual Basic では Nothing) です。 |
ArgumentException | path が空の文字列 ("") か、空白しか含んでいないか、無効な文字を 1 つ以上含んでいます。 または path がファイル以外のデバイスを参照しています (NTFS 環境の "con:"、"com1:"、"lpt1:" など)。 |
NotSupportedException | path がファイル以外のデバイスを参照しています (NTFS 以外の環境の "con:"、"com1:"、"lpt1:" など)。 |
ArgumentException | |
ArgumentOutOfRangeException | bufferSize が負の値またはゼロです。 または |
FileNotFoundException | ファイルが見つかりません。たとえば、mode が FileMode.Truncate または FileMode.Open の場合に、path で指定されたファイルが存在しません。これらのモードでは、ファイルが既に存在している必要があります。 |
IOException | FileMode.CreateNew が指定されているのに、path で指定したファイルが既に存在していることなどが原因で I/O エラーが発生しました。 または システムで Windows 98 または Windows 98 Second Edition を実行しており、share が FileShare.Delete に設定されています。 または |
SecurityException | |
DirectoryNotFoundException | |
UnauthorizedAccessException | access が Write または ReadWrite であるのに、ファイルまたはディレクトリが読み取り専用に設定されているなど、指定した path に対する access 要求がオペレーティング システムで許可されません。 |
PathTooLongException | 指定したパス、ファイル名、またはその両方がシステム定義の最大長を超えています。たとえば、Windows ベースのプラットフォームの場合、パスの長さは 248 文字未満、ファイル名の長さは 260 文字未満である必要があります。 |

.NET Framework では、"\\.\PHYSICALDRIVE0" など、デバイス名を指定したパスを使用して物理ディスクに直接アクセスすることはできません。
path パラメータにはファイル名も指定できます。このファイルには、UNC 共有のファイルも含まれます。
![]() |
---|
特定のカルチャ設定で文字セットをコンパイルし、同じ文字を異なるカルチャ設定で取得すると、文字が正しく解釈されない場合があり、例外がスローされることもあります。 |
その他の一般的な 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 |


Windows 98, Windows 2000 SP4, Windows Millennium Edition, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition
開発プラットフォームの中には、.NET Framework によってサポートされていないバージョンがあります。サポートされているバージョンについては、「システム要件」を参照してください。


FileStream コンストラクタ (IntPtr, FileAccess)
メモ : このコンストラクタは、互換性のために残されています。
FileStream クラスの新しいインスタンスを、指定した読み取り/書き込みアクセス許可を使用して、指定したファイル ハンドル用に初期化します。 名前空間: System.IOアセンブリ: mscorlib (mscorlib.dll 内)

<ObsoleteAttribute("This constructor has been deprecated. Please use new FileStream(SafeFileHandle handle, FileAccess access) instead. http://go.microsoft.com/fwlink/?linkid=14202")> _ Public Sub New ( _ handle As IntPtr, _ access As FileAccess _ )
[ObsoleteAttribute("This constructor has been deprecated. Please use new FileStream(SafeFileHandle handle, FileAccess access) instead. http://go.microsoft.com/fwlink/?linkid=14202")] public FileStream ( IntPtr handle, FileAccess access )
[ObsoleteAttribute(L"This constructor has been deprecated. Please use new FileStream(SafeFileHandle handle, FileAccess access) instead. http://go.microsoft.com/fwlink/?linkid=14202")] public: FileStream ( IntPtr handle, FileAccess access )
/** @attribute ObsoleteAttribute("This constructor has been deprecated. Please use new FileStream(SafeFileHandle handle, FileAccess access) instead. http://go.microsoft.com/fwlink/?linkid=14202") */ public FileStream ( IntPtr handle, FileAccess access )
ObsoleteAttribute("This constructor has been deprecated. Please use new FileStream(SafeFileHandle handle, FileAccess access) instead. http://go.microsoft.com/fwlink/?linkid=14202") public function FileStream ( handle : IntPtr, access : FileAccess )


Close が呼び出されると、ハンドルも閉じられ、ファイルのハンドル カウントがデクリメントされます。
FileStream は、ハンドルを排他的に制御していると見なされます。FileStream がハンドルも保持しているときに、読み取り、書き込み、またはシークを実行すると、データが破損することがあります。データを保護するために、ハンドルを使用する前に Flush を呼び出し、ハンドルの使用後は Close 以外のメソッドを呼び出さないようにします。
![]() |
---|
特定のカルチャ設定で文字セットをコンパイルし、同じ文字を異なるカルチャ設定で取得すると、文字が正しく解釈されない場合があり、例外がスローされることもあります。 |
FileShare パラメータを指定しないタイプの FileStream コンストラクタに対しては、FileShare.Read が既定値です。
その他の一般的な 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 |


Windows 98, Windows 2000 SP4, Windows Millennium Edition, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition
開発プラットフォームの中には、.NET Framework によってサポートされていないバージョンがあります。サポートされているバージョンについては、「システム要件」を参照してください。


FileStream プロパティ

名前 | 説明 | |
---|---|---|
![]() | CanTimeout | 現在のストリームがタイムアウトできるかどうかを決定する値を取得します。 ( Stream から継承されます。) |
![]() | ReadTimeout | ストリームがタイムアウト前に読み取りを試行する期間を決定する値を取得または設定します。 ( Stream から継承されます。) |
![]() | WriteTimeout | ストリームがタイムアウト前に書き込みを試行する期間を決定する値を取得または設定します。 ( Stream から継承されます。) |

FileStream メソッド


名前 | 説明 | |
---|---|---|
![]() | CreateWaitHandle | WaitHandle オブジェクトを割り当てます。 ( Stream から継承されます。) |
![]() | Dispose | オーバーロードされます。 オーバーライドされます。 |
![]() | Finalize | オーバーライドされます。 ガベージ コレクタが FileStream を利用しているときに、リソースの解放およびその他のクリーンアップ操作を確実に実行します。 |
![]() | MemberwiseClone | オーバーロードされます。 ( MarshalByRefObject から継承されます。) |

FileStream メンバ
同期および非同期の読み取り操作と書き込み操作をサポートするファイル用の Stream を公開します。
FileStream データ型で公開されるメンバを以下の表に示します。


名前 | 説明 | |
---|---|---|
![]() | CanTimeout | 現在のストリームがタイムアウトできるかどうかを決定する値を取得します。(Stream から継承されます。) |
![]() | ReadTimeout | ストリームがタイムアウト前に読み取りを試行する期間を決定する値を取得または設定します。 (Stream から継承されます。) |
![]() | WriteTimeout | ストリームがタイムアウト前に書き込みを試行する期間を決定する値を取得または設定します。 (Stream から継承されます。) |


名前 | 説明 | |
---|---|---|
![]() | CreateWaitHandle | WaitHandle オブジェクトを割り当てます。 (Stream から継承されます。) |
![]() | Dispose | オーバーロードされます。 オーバーライドされます。 |
![]() | Finalize | オーバーライドされます。 ガベージ コレクタが FileStream を利用しているときに、リソースの解放およびその他のクリーンアップ操作を確実に実行します。 |
![]() | MemberwiseClone | オーバーロードされます。 ( MarshalByRefObject から継承されます。) |

- FileStreamのページへのリンク