FileStream クラスとは? わかりやすく解説

FileStream クラス

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

名前空間: System.IO
アセンブリ: mscorlib (mscorlib.dll 内)
構文構文

<ComVisibleAttribute(True)> _
Public Class FileStream
    Inherits Stream
[ComVisibleAttribute(true)] 
public class FileStream : Stream
[ComVisibleAttribute(true)] 
public ref class FileStream : public
 Stream
/** @attribute ComVisibleAttribute(true) */ 
public class FileStream extends Stream
ComVisibleAttribute(true) 
public class FileStream extends
 Stream
解説解説

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

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

メモメモ

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

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

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

特にディスク容量制限され環境では、すべての FileStream オブジェクトに対してDispose メソッドを必ず呼び出します。使用できるディスク容量がなく、FileStream終了する前に Dispose メソッド呼び出されていない場合IO 操作実行する例外発生する可能性あります

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

その他の一般的な I/O タスクまたは関連する I/O タスクの例を次の表に示します

ストリームの位置の変更の検出

FileStream オブジェクトハンドル排他的に保持してない場合別のスレッド同時にファイル ハンドルアクセスし、ファイル ハンドル関連付けられたオペレーティング システムファイル ポインタ位置変更する可能性あります。この場合FileStream オブジェクト内にキャッシュされた位置バッファ内にキャッシュされたデータ侵害される可能性ありますFileStream オブジェクトは、キャッシュされたバッファアクセスするメソッド定期的にチェックしてオペレーティング システムハンドル位置FileStream オブジェクト使用されるキャッシュされた位置と同じであることを保証します

Read メソッド呼び出し時にハンドル位置予期しない変更検出され場合.NET Frameworkバッファ内容破棄しファイルかストリーム再度読み取ります。ファイルサイズや、ファイル ストリーム位置影響を及ぼす可能性のある他のプロセスによっては、これはパフォーマンス影響する場合あります

Write メソッド呼び出し時にハンドル位置予期しない変更検出され場合には、バッファ内容破棄され、IOException がスローさます。

SafeFileHandle プロパティ使用してハンドル公開した場合、またはコンストラクタFileStream オブジェクトSafeFileHandle プロパティ指定され場合に、FileStream オブジェクトハンドル排他的に保持しなくなります

使用例使用例

FileStream コンストラクタいくつか使用する例を次に示します

Imports System
Imports System.IO
Imports System.Text

Public Class Test

    Public Shared Sub Main()
        Dim path As String
 = "c:\temp\MyTest.txt"

        ' Delete the file if it exists.
        If File.Exists(path) Then
            File.Delete(path)
        End If

        'Create the file.
        Dim fs As FileStream = File.Create(path)

        AddText(fs, "This is some text")
        AddText(fs, "This is some more text,")
        AddText(fs, Environment.NewLine & "and this is on
 a new line")
        AddText(fs, Environment.NewLine & Environment.NewLine)
        AddText(fs, "The following is a subset of characters:"
 & Environment.NewLine)

        Dim i As Integer

        For i = 1 To 120
            AddText(fs, Convert.ToChar(i).ToString())

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

        fs.Close()

        'Open the stream and read it back.
        fs = File.OpenRead(path)
        Dim b(1024) As Byte
        Dim temp As UTF8Encoding = New
 UTF8Encoding(True)

        Do While fs.Read(b, 0, b.Length) >
 0
            Console.WriteLine(temp.GetString(b))
        Loop

        fs.Close()
    End Sub

    Private Shared Sub AddText(ByVal
 fs As FileStream, ByVal value As
 String)
        Dim info As Byte()
 = New UTF8Encoding(True).GetBytes(value)
        fs.Write(info, 0, info.Length)
    End Sub
End Class
using System;
using System.IO;
using System.Text;

class Test 
{
    
    public static void Main()
 
    {
        string path = @"c:\temp\MyTest.txt";

        // Delete the file if it exists.
        if (File.Exists(path)) 
        {
            File.Delete(path);
        }

        //Create the file.
        using (FileStream fs = File.Create(path)) 
        {
            AddText(fs, "This is some text");
            AddText(fs, "This is some more text,");
            AddText(fs, "\r\nand this is on a new
 line");
            AddText(fs, "\r\n\r\nThe following is a subset of characters:\r\n");

            for (int i=1;i < 120;i++) 
            {
                AddText(fs, Convert.ToChar(i).ToString());

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

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

    private static void
 AddText(FileStream fs, string value) 
    {
        byte[] info = new UTF8Encoding(true).GetBytes(value);
        fs.Write(info, 0, info.Length);
    }
}
using namespace System;
using namespace System::IO;
using namespace System::Text;

void AddText( FileStream^ fs, String^ value )
{
   array<Byte>^info = (gcnew UTF8Encoding( true ))->GetBytes(
 value );
   fs->Write( info, 0, info->Length );
}

int main()
{
   String^ path = "c:\\temp\\MyTest.txt";
   
   // Delete the file if it exists.
   if ( File::Exists( path ) )
   {
      File::Delete( path );
   }

   //Create the file.
   {
      FileStream^ fs = File::Create( path );
      try
      {
         AddText( fs, "This is some text" );
         AddText( fs, "This is some more text," );
         AddText( fs, "\r\nand this is on a new
 line" );
         AddText( fs, "\r\n\r\nThe following is a subset of characters:\r\n"
 );
         for ( int i = 1; i < 120; i++ )
         {
            AddText( fs, Convert::ToChar( i ).ToString() );
            
            //Split the output at every 10th character.
            if ( Math::IEEERemainder( Convert::ToDouble( i ),
 10 ) == 0 )
            {
               AddText( fs, "\r\n" );
            }
         }
      }
      finally
      {
         if ( fs )
            delete (IDisposable^)fs;
      }
   }
   
   //Open the stream and read it back.
   {
      FileStream^ fs = File::OpenRead( path );
      try
      {
         array<Byte>^b = gcnew array<Byte>(1024);
         UTF8Encoding^ temp = gcnew UTF8Encoding( true );
         while ( fs->Read( b, 0, b->Length ) > 0 )
         {
            Console::WriteLine( temp->GetString( b ) );
         }
      }
      finally
      {
         if ( fs )
            delete (IDisposable^)fs;
      }
   }
}
import System.*;
import System.IO.*;
import System.Text.*;

class Test
{
    public static void main(String[]
 args)
    {
        String path = "c:\\temp\\MyTest.txt";

        // Delete the file if it exists.
        if (File.Exists(path)) {
            File.Delete(path);
        }
        
        //Create the file.
        {
            FileStream fs = File.Create(path);
            try {
                AddText(fs, "This is some text");
                AddText(fs, "This is some more text,");
                AddText(fs, "\r\nand this is on a new
 line");
                AddText(fs, 
                    "\r\n\r\nThe following is a subset of characters:\r\n");
                for (int i = 1; i < 120;
 i++) {
                    AddText(fs, System.Convert.ToString((char)i));

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

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

ファイルを開くか、ファイル存在しない場合ファイル作成して、そのファイル末尾情報追加する例を次に示します

Imports System
Imports System.IO
Imports System.Text

Class FSOpenWrite

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

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

継承階層継承階層
System.Object
   System.MarshalByRefObject
     System.IO.Stream
      System.IO.FileStream
         System.IO.IsolatedStorage.IsolatedStorageFileStream
スレッド セーフスレッド セーフ
この型の public static (Visual Basic では Shared) メンバはすべて、スレッド セーフです。インスタンス メンバ場合は、スレッド セーフであるとは限りません。
プラットフォームプラットフォーム
バージョン情報バージョン情報
参照参照



英和和英テキスト翻訳>> Weblio翻訳
英語⇒日本語日本語⇒英語
  

辞書ショートカット

すべての辞書の索引

「FileStream クラス」の関連用語

FileStream クラスのお隣キーワード
検索ランキング

   

英語⇒日本語
日本語⇒英語
   



FileStream クラスのページの著作権
Weblio 辞書 情報提供元は 参加元一覧 にて確認できます。

   
日本マイクロソフト株式会社日本マイクロソフト株式会社
© 2024 Microsoft.All rights reserved.

©2024 GRAS Group, Inc.RSS