FileStream.Seek(Int64, SeekOrigin) Méthode

Définition

Définit la position actuelle de ce flux avec la valeur donnée.

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

Paramètres

offset
Int64

Point relatif à l'élément origin où la recherche doit commencer.

origin
SeekOrigin

Spécifie le début, la fin ou la position actuelle comme point de référence pour offset, en utilisant une valeur de type SeekOrigin.

Retours

Nouvelle position dans le flux.

Exceptions

Une erreur d'E/S s'est produite.

Le flux ne prend pas en charge la recherche, notamment comme si le FileStream était construit à partir d’une sortie de canal ou de la console.

Tentative de recherche avant le début du flux.

Des méthodes ont été appelées après la fermeture du flux.

Exemples

L’exemple suivant montre comment écrire des données dans un fichier, octet par octet, puis vérifier que les données ont été écrites correctement.

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

L’exemple suivant lit le texte dans la direction inverse, de la fin du fichier au début du fichier, en utilisant les différentes SeekOrigin valeurs avec la Seek méthode .

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

Remarques

Cette méthode se substitue à Stream.Seek.

Notes

Utilisez la FileStream.CanSeek propriété pour déterminer si l’instance actuelle prend en charge la recherche. Pour plus d'informations, consultez Stream.CanSeek.

Vous pouvez rechercher n’importe quel emplacement au-delà de la longueur du flux. Lorsque vous recherchez au-delà de la longueur du fichier, la taille du fichier augmente. Les données ajoutées à la fin du fichier sont définies sur zéro.

Pour obtenir la liste des opérations courantes de fichiers et de répertoires, consultez Tâches courantes d’E/S.

S’applique à

Voir aussi