FileStream.Seek(Int64, SeekOrigin) メソッド

定義

このストリームの現在位置を特定の値に設定します。

public:
 override long Seek(long offset, System::IO::SeekOrigin origin);
public override long Seek (long offset, System.IO.SeekOrigin origin);
override this.Seek : int64 * System.IO.SeekOrigin -> int64
Public Overrides Function Seek (offset As Long, origin As SeekOrigin) As Long

パラメーター

offset
Int64

シークの開始位置を示す、origin に対する相対ポイント。

origin
SeekOrigin

SeekOrigin 型の値を使用して、offset の参照ポイントとして先頭、末尾、または現在位置を指定します。

戻り値

Int64

ストリームの新しい位置。

例外

I/O エラーが発生しました。

ストリームがシークをサポートしていません。たとえば、FileStream がパイプまたはコンソール出力から構築されました。

シークがストリームの開始前に試行されています。

ストリームが閉じた後でメソッドが呼び出されました。

次の例は、データをファイルにバイト単位で書き込み、データが正しく書き込まれたことを確認する方法を示しています。

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();
   }

}
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);
        }
    }
}
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

次の例では、メソッドでさまざまな SeekOrigin 値を使用して、ファイルの末尾からファイルの先頭まで、逆方向のテキストを Seek 読み取ります。

using System;
using System.IO;

public class FSSeek
{
    public static void Main()
    {
        long offset;
        int nextByte;

        // alphabet.txt contains "abcdefghijklmnopqrstuvwxyz"
        using (FileStream fs = new FileStream(@"c:\temp\alphabet.txt", FileMode.Open, FileAccess.Read))
        {
            for (offset = 1; offset <= fs.Length; offset++)
            {
                fs.Seek(-offset, SeekOrigin.End);
                Console.Write((char)fs.ReadByte());
            }
            Console.WriteLine();

            fs.Seek(20, SeekOrigin.Begin);

            while ((nextByte = fs.ReadByte()) > 0)
            {
                Console.Write((char)nextByte);
            }
            Console.WriteLine();
        }
    }
}
// This code example displays the following output:
//
// zyxwvutsrqponmlkjihgfedcba
// uvwxyz
Imports System.IO

Public Class FSSeek
    Public Shared Sub Main()
        Dim offset As Long
        Dim nextByte As Integer

        ' alphabet.txt contains "abcdefghijklmnopqrstuvwxyz"
        Using fs As New FileStream("c:\temp\alphabet.txt", FileMode.Open, FileAccess.Read)

            For offset = 1 To fs.Length
                fs.Seek(-offset, SeekOrigin.End)
                Console.Write(Convert.ToChar(fs.ReadByte()))
            Next offset
            Console.WriteLine()

            fs.Seek(20, SeekOrigin.Begin)

            nextByte = fs.ReadByte()
            While (nextByte > 0)
                Console.Write(Convert.ToChar(nextByte))
                nextByte = fs.ReadByte()
            End While
            Console.WriteLine()

        End Using
    End Sub
End Class

' This code example displays the following output:
'
' zyxwvutsrqponmlkjihgfedcba
' uvwxyz

注釈

このメソッドは、Stream.Seek をオーバーライドします。

注意

プロパティを FileStream.CanSeek 使用して、現在のインスタンスがシークをサポートしているかどうかを判断します。 詳細については、「Stream.CanSeek」を参照してください。

ストリームの長さを超える任意の場所にシークできます。 ファイルの長さを超えてシークすると、ファイル サイズが大きくなります。 ファイルの末尾に追加されたデータは 0 に設定されます。

一般的なファイル操作とディレクトリ操作の一覧については、「 一般的な I/O タスク」を参照してください。

適用対象

こちらもご覧ください