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에 대한 참조 지점으로 지정합니다.

반환

스트림 내의 새 위치입니다.

예외

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);
        }
    }
}
open System
open System.IO


let fileName = "Test#@@#.dat"

// Create random data to write to the file.
let dataArray = Array.zeroCreate 100000
Random.Shared.NextBytes dataArray

do
    use fileStream = new FileStream(fileName, FileMode.Create)
    // Write the data to the file, byte by byte.
    for i = 0 to dataArray.Length - 1 do
        fileStream.WriteByte dataArray[i]

    // Set the stream position to the beginning of the file.
    fileStream.Seek(0, SeekOrigin.Begin) |> ignore

    // Read and verify the data.
    for i in 0L .. fileStream.Length - 1L do
        if dataArray[int i] <> (fileStream.ReadByte() |> byte) then
            printfn "Error writing data."
            exit 1

    printfn $"The data was written to {fileStream.Name} and verified."
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

다음 예제에서는 메서드와 함께 Seek 다양한 SeekOrigin 값을 사용하여 파일 끝에서 파일의 시작까지 반대 방향으로 텍스트를 읽습니다.

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
open System.IO

// alphabet.txt contains "abcdefghijklmnopqrstuvwxyz"
using (new FileStream(@"c:\temp\alphabet.txt", FileMode.Open, FileAccess.Read)) (fun fs ->
    for offset in 1L .. fs.Length do
        fs.Seek(-offset, SeekOrigin.End) |> ignore
        printf $"{fs.ReadByte() |> char}"

    printfn ""

    fs.Seek(20, SeekOrigin.Begin) |> ignore

    let mutable nextByte = fs.ReadByte()

    while nextByte > 0 do
        printf $"{char nextByte}"
        nextByte <- fs.ReadByte())

// 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 작업을 참조하세요.

적용 대상

추가 정보