Personas que lo han encontrado útil: 0 de 1 - Valorar este tema

FileStream.Seek (Método)

Establece la posición actual de esta secuencia actual en el valor dado.

Espacio de nombres: System.IO
Ensamblado: mscorlib (en mscorlib.dll)

public override long Seek (
	long offset,
	SeekOrigin origin
)
public long Seek (
	long offset, 
	SeekOrigin origin
)
public override function Seek (
	offset : long, 
	origin : SeekOrigin
) : long

Parámetros

offset

El punto relativo a origin desde el que comienza la operación Seek.

origin

Especifica el comienzo, el final o la posición actual como un punto de referencia para origin, mediante el uso de un valor de tipo SeekOrigin.

Valor devuelto

La nueva posición en la secuencia.
Tipo de excepción Condición

IOException

Se produce un error de E/S.

NotSupportedException

La secuencia no admite operaciones Seek, como sucede cuando se crea FileStream a partir de una canalización o una salida a la consola.

ArgumentException

Se ha intentado realizar una búsqueda antes del inicio de la secuencia.

ObjectDisposedException

Tras cerrar la secuencia, se llamó a algún método.

Este método reemplaza a Seek.

NotaNota

Se utiliza la propiedad CanSeek para determinar si la instancia actual admite búsquedas. Para obtener más información, vea CanSeek.

Se admite la búsqueda de cualquier ubicación más allá de la longitud de la secuencia. Cuando se busca más allá de la longitud del archivo, el tamaño del archivo crece. En Microsoft Windows NT y versiones posteriores, los datos agregados al final del archivo se establecen en cero. En Microsoft Windows 98 o versiones anteriores, los datos agregados al final del archivo no se establecen en cero, lo que significa que los datos previamente eliminados están visibles para la secuencia.

En la siguiente tabla se muestran ejemplos de otras tareas de E/S típicas o relacionadas.

Para realizar esta operación...

Vea el ejemplo de este tema...

Crear un archivo de texto

Cómo: Escribir texto en un archivo

Escribir en un archivo de texto

Cómo: Escribir texto en un archivo

Leer de un archivo de texto

Cómo: Leer texto de un archivo

Anexar texto a un archivo

Cómo: Abrir y anexar a un archivo de registro

File.AppendText

FileInfo.AppendText

Cambiar de nombre o mover un archivo

File.Move

FileInfo.MoveTo

Copiar un archivo

File.Copy

FileInfo.CopyTo

Obtener el tamaño de un directorio

FileInfo.Length

Obtener los atributos de un archivo

File.GetAttributes

Establecer los atributos de un archivo

File.SetAttributes

Crear un subdirectorio

CreateSubdirectory

Leer de un archivo binario

Cómo: Leer y escribir en un archivo de datos recién creado

Escribir en un archivo binario

Cómo: Leer y escribir en un archivo de datos recién creado

Ver los archivos de un directorio

Name

Ordenar por tamaño los archivos de un directorio

GetFileSystemInfos

En el ejemplo de código siguiente se muestra la forma de escribir datos en un archivo, byte a byte, y cómo se comprueba después que los datos se han escrito correctamente.

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

import System.*;
import System.IO.*;

class FStream
{   
    public static void main(String[] args)
    {
        final String fileName = "Test#@@#.dat";

        // Create random data to write to the file.
        ubyte dataArray[] = new ubyte[100000];
        new Random().NextBytes(dataArray);        

        FileStream fileStream = new 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.get_Length();i++) {
                if ( dataArray[i] != fileStream.ReadByte()  ) {
                    Console.WriteLine("Error writing data.");
                    return;
                }
            } 
            Console.WriteLine("The data was written to {0} "
                + "and verified.", fileStream.get_Name());
        }
        finally {
            fileStream.Dispose();
        }        
    } //main
} //FStream

Windows 98, Windows 2000 SP4, Windows CE, Windows Millennium, Windows Mobile para Pocket PC, Windows Mobile para Smartphone, Windows Server 2003, Windows XP Media Center, Windows XP Professional x64, Windows XP SP2, Windows XP Starter Edition

.NET Framework no admite todas las versiones de cada plataforma. Para obtener una lista de las versiones admitidas, vea Requisitos del sistema.

.NET Framework

Compatible con: 2.0, 1.1, 1.0

.NET Compact Framework

Compatible con: 2.0, 1.0
¿Le ha resultado útil?
(Caracteres restantes: 1500)
Contenido de la comunidad Agregar