FileStream.Seek(Int64, SeekOrigin) FileStream.Seek(Int64, SeekOrigin) FileStream.Seek(Int64, SeekOrigin) FileStream.Seek(Int64, SeekOrigin) Method

Definizione

Imposta la posizione corrente del flusso sul valore dato.Sets the current position of this stream to the given value.

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

Parametri

offset
Int64 Int64 Int64 Int64

Punto relativo a origin da cui avviare la ricerca.The point relative to origin from which to begin seeking.

origin
SeekOrigin SeekOrigin SeekOrigin SeekOrigin

Specifica l'inizio, la fine o la posizione corrente come punto di riferimento per offset, usando un valore di tipo SeekOrigin.Specifies the beginning, the end, or the current position as a reference point for offset, using a value of type SeekOrigin.

Restituisce

Nuova posizione all'interno del flusso.The new position in the stream.

Eccezioni

Si è verificato un errore di I/O.An I/O error occurred.

Il flusso non supporta la ricerca, ad esempio se l'oggetto FileStream viene costruito da una pipe o da un output di console.The stream does not support seeking, such as if the FileStream is constructed from a pipe or console output.

La ricerca viene tentata prima dell'inizio del flusso.Seeking is attempted before the beginning of the stream.

Sono stati chiamati dei metodi dopo la chiusura del flusso.Methods were called after the stream was closed.

Esempi

Nell'esempio seguente viene illustrato come scrivere dati in un file, byte per byte e quindi verificare che i dati siano stati scritti correttamente.The following example shows how to write data to a file, byte by byte, and then verify that the data was written correctly.

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

Nell'esempio seguente viene letto il testo nella direzione inversa, dalla fine del file all'inizio del file, usando i vari SeekOrigin valori con il Seek metodo.The following example reads text in the reverse direction, from the end of file to the beginning of the file, by using the various SeekOrigin values with the Seek method.

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(Convert.ToChar(fs.ReadByte()));
            }
            Console.WriteLine();

            fs.Seek(20, SeekOrigin.Begin);

            while ((nextByte = fs.ReadByte()) > 0)
            {
                Console.Write(Convert.ToChar(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

Commenti

Questo metodo esegue l'override del metodo Stream.Seek.This method overrides Stream.Seek.

Nota

Utilizzare la FileStream.CanSeek proprietà per determinare se l'istanza corrente supporta la ricerca.Use the FileStream.CanSeek property to determine whether the current instance supports seeking. Per altre informazioni, vedere Stream.CanSeek.For additional information, see Stream.CanSeek.

È possibile cercare in qualsiasi posizione oltre la lunghezza del flusso.You can seek to any location beyond the length of the stream. Quando si cerca di superare la lunghezza del file, le dimensioni del file aumentano.When you seek beyond the length of the file, the file size grows. In Windows NT e versioni successive i dati aggiunti alla fine del file sono impostati su zero.In Windows NT and later versions, data added to the end of the file is set to zero. In Windows 98 o versioni precedenti, i dati aggiunti alla fine del file non sono impostati su zero, il che significa che i dati eliminati in precedenza sono visibili al flusso.In Windows 98 or earlier versions, data added to the end of the file is not set to zero, which means that previously deleted data is visible to the stream.

Per un elenco delle operazioni comuni di file e directory, vedere attività di I/O comuni.For a list of common file and directory operations, see Common I/O Tasks.

Si applica a

Vedi anche