次の方法で共有


FileStream コンストラクタ (String, FileMode, FileAccess, FileShare, Int32, Boolean)

FileStream クラスの新しいインスタンスを、指定したパス、作成モード、読み取り/書き込みアクセス許可、共有アクセス許可、バッファ サイズ、および同期状態または非同期状態を使用して初期化します。

名前空間: System.IO
アセンブリ: 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
)

パラメータ

  • path
    現在の FileStream オブジェクトによってカプセル化されるファイルの相対パスまたは絶対パス。
  • mode
    ファイルを開く方法または作成する方法を決定する FileMode 定数。
  • access
    FileStream オブジェクトがファイルにアクセスする方法を決定する FileAccess 定数。これは、FileStream オブジェクトの CanRead プロパティと CanWrite プロパティを取得します。path にディスク ファイルが指定されている場合、CanSeektrue になります。
  • share
    プロセスによるファイルの共有方法を決定する FileShare 定数。
  • bufferSize
    バッファ サイズを示す 0 より大きな正の Int32 値。bufferSize 値には 0 から 8 を設定します。実際のバッファ サイズは 8 バイトに設定されます。
  • 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

path が空の文字列 ("") か、空白しか含んでいないか、無効な文字を 1 つ以上含んでいます。

ArgumentOutOfRangeException

bufferSize が負の値またはゼロです。

または

mode、access、または share に無効な値が含まれています。

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 共有のファイルも含まれます。

注意

path は、ディスクに格納されているファイルである必要はありません。ストリーム経由でアクセスできるシステム上の任意の個所を指定できます。たとえば、システムによっては、このクラスで物理デバイスにアクセスできることもあります。

CanSeek は、ファイルをカプセル化するすべての FileStream オブジェクトで true です。path がシークをサポートしないデバイスを示している場合、結果として得られる FileStreamCanSeek プロパティは false です。詳細については、CanSeek のトピックを参照してください。

ヒント

特定のカルチャ設定で文字セットをコンパイルし、同じ文字を異なるカルチャ設定で取得すると、文字が正しく解釈されない場合があり、例外がスローされることもあります。

その他の一般的な 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

使用例

ファイルにデータを非同期的に書き込み、さらにデータが正常に書き込まれたことを確認する例を次に示します。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

.NET Framework のセキュリティ

プラットフォーム

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 によってサポートされていないバージョンがあります。サポートされているバージョンについては、「システム要件」を参照してください。

バージョン情報

.NET Framework

サポート対象 : 2.0、1.1、1.0

.NET Compact Framework

サポート対象 : 2.0、1.0

参照

関連項目

FileStream クラス
FileStream メンバ
System.IO 名前空間
File クラス

その他の技術情報

ファイルおよびストリーム入出力
方法 : ファイルからテキストを読み取る
方法 : ファイルにテキストを書き込む