Este tema aún no ha recibido ninguna valoración - Valorar este tema

FileStream (Constructor) (String, FileMode, FileAccess, FileShare, Int32, Boolean)

Inicializa una nueva instancia de la clase FileStream con el estado sincrónico o asincrónico, el tamaño de búfer, el permiso de lectura/escritura y de uso compartido, el modo de creación y la ruta de acceso especificados.

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

public FileStream (
	string path,
	FileMode mode,
	FileAccess access,
	FileShare share,
	int bufferSize,
	bool useAsync
)
public FileStream (
	String path, 
	FileMode mode, 
	FileAccess access, 
	FileShare share, 
	int bufferSize, 
	boolean useAsync
)
public function FileStream (
	path : String, 
	mode : FileMode, 
	access : FileAccess, 
	share : FileShare, 
	bufferSize : int, 
	useAsync : boolean
)

Parámetros

path

Ruta relativa o absoluta del archivo que va a encapsular el objeto FileStream actual.

mode

Constante de FileMode que determina cómo abrir o crear el archivo.

access

Constante de FileAccess que determina cómo el objeto FileStream puede obtener acceso al archivo. Obtiene las propiedades CanRead y CanWrite del objeto FileStream. CanSeek es true si path especifica un archivo de disco.

share

Una constante de FileShare que determina cómo los procesos compartirán el archivo.

bufferSize

Valor Int32 positivo mayor que 0 que indica el tamaño del búfer. Para valores de bufferSize entre cero y ocho, el tamaño de búfer real se establece en ocho bytes.

useAsync

Especifica si se va a utilizar la E/S asincrónica o E/S sincrónica. No obstante, tenga en cuenta que es posible que el sistema operativo subyacente no admita la E/S asincrónica, por lo que al especificar true, puede que el identificador se abra de forma sincrónica dependiendo de la plataforma. Cuando se abre de forma asincrónica, los métodos BeginRead y BeginWrite proporcionan un rendimiento mejor en lecturas o escrituras grandes, pero es posible que sean mucho más lentos para lecturas o escrituras pequeñas. Si la aplicación se ha diseñado para aprovechar al máximo la E/S asincrónica, establezca el parámetro useAsync en true. El uso de la E/S asincrónica de forma correcta puede agilizar las aplicaciones en hasta un factor de 10, pero su uso sin volver a diseñar la aplicación para la E/S asincrónica puede disminuir el rendimiento en hasta un factor de 10.

Tipo de excepción Condición

ArgumentNullException

path es referencia de objeto null (Nothing en Visual Basic).

ArgumentException

path es una cadena vacía (""), contiene sólo espacios en blanco o contiene uno o varios caracteres no válidos.

O bien

path hace referencia a un dispositivo que no es un archivo, como "con:", "com1:", "lpt1:", etc. en un entorno NTFS.

NotSupportedException

path hace referencia a un dispositivo que no es un archivo, como "con:", "com1:", "lpt1:", etc. en un entorno que no es NTFS.

ArgumentException

path es una cadena vacía (""), contiene sólo espacios en blanco o contiene uno o varios caracteres no válidos.

ArgumentOutOfRangeException

bufferSize es un valor negativo o es cero.

O bien

mode, access o share contienen un valor no válido.

FileNotFoundException

No se encuentra el archivo, como cuando mode es FileMode.Truncate o FileMode.Open, y no existe el archivo especificado por path. El archivo ya debe existir en estos modos.

IOException

Se produce un error de E/S, como cuando se especifica FileMode.CreateNew y ya existe el archivo especificado por path.

O bien

El sistema está ejecutando Windows 98 o Windows 98 Segunda edición y se ha establecido share en FileShare.Delete.

O bien

Se ha cerrado la secuencia.

SecurityException

El llamador no dispone del permiso requerido.

DirectoryNotFoundException

La ruta de acceso especificada no es válida como, por ejemplo, una ruta de una unidad no asignada.

UnauthorizedAccessException

El sistema operativo no permite el access solicitado para el path especificado, como sucede, por ejemplo, cuando access es Write o ReadWrite y el archivo o el directorio está establecido para el acceso de sólo lectura.

PathTooLongException

La ruta de acceso especificada, el nombre de archivo o ambos superan la longitud máxima definida por el sistema. Por ejemplo, en las plataformas basadas en Windows, las rutas de acceso deben ser inferiores a 248 caracteres y los nombres de archivo deben ser inferiores a 260 caracteres.

.NET Framework no admite el acceso directo a discos físicos a través de rutas de acceso que sean nombres de dispositivo, como "\\.\UNIDADFÍSICA0 ".

El parámetro path puede ser un nombre de archivo, incluido un archivo en un recurso compartido UNC (Convención de nomenclatura universal).

NotaNota

No es necesario que path sea un archivo almacenado en disco; puede formar parte de un sistema que admita el acceso a través de secuencias. Por ejemplo, dependiendo del sistema, esta clase puede tener acceso a un dispositivo físico.

CanSeek es true para todos los objetos FileStream que encapsulan archivos. Si path indica un dispositivo que no es compatible con las búsquedas seek, la propiedad CanSeek del FileStream resultante es false. Para obtener más información, vea CanSeek.

Nota de precauciónPrecaución

Cuando se compila un conjunto de caracteres con una configuración de referencia cultural concreta y se recuperan los mismos caracteres con una configuración de referencia cultural diferente, es posible que los caracteres no se puedan interpretar y podría producirse una excepción.

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

Eliminar un archivo

File.Delete

FileInfo.Delete

Copiar un archivo

File.Copy

FileInfo.CopyTo

Obtener el tamaño de un archivo

FileInfo.Length

Obtener los atributos de un archivo

File.GetAttributes

Establecer los atributos de un archivo

File.SetAttributes

Determinar si un archivo existe

File.Exists

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

Recuperar una extensión de archivo

Path.GetExtension

Recuperar la ruta de acceso completa de un archivo

Path.GetFullPath

Recuperar el nombre de archivo y la extensión de una ruta de acceso

Path.GetFileName

Cambiar la extensión de un archivo

Path.ChangeExtension

En el ejemplo de código siguiente se muestra la forma de escribir datos en un archivo de forma asincrónica y cómo se comprueba después que los datos se han escrito correctamente. Se crea un objeto State para pasar información del subproceso principal a los métodos EndReadCallback y EndWriteCallback.

using System;
using System.IO;
using System.Threading;

class FStream
{
    static void Main()
    {
        // Create a synchronization object that gets 
        // signaled when verification is complete.
        ManualResetEvent manualEvent = new ManualResetEvent(false);

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

        FileStream fStream = 
            new FileStream("Test#@@#.dat", FileMode.Create, 
            FileAccess.ReadWrite, FileShare.None, 4096, true);

        // Check that the FileStream was opened asynchronously.
        Console.WriteLine("fStream was {0}opened asynchronously.",
            fStream.IsAsync ? "" : "not ");

        // Asynchronously write to the file.
        IAsyncResult asyncResult = fStream.BeginWrite(
            writeArray, 0, writeArray.Length, 
            new AsyncCallback(EndWriteCallback), 
            new State(fStream, writeArray, manualEvent));

        // Concurrently do other work and then wait 
        // for the data to be written and verified.
        manualEvent.WaitOne(5000, false);
    }

    // When BeginWrite is finished writing data to the file, the
    // EndWriteCallback method is called to end the asynchronous 
    // write operation and then read back and verify the data.
    static void EndWriteCallback(IAsyncResult asyncResult)
    {
        State tempState = (State)asyncResult.AsyncState;
        FileStream fStream = tempState.FStream;
        fStream.EndWrite(asyncResult);

        // Asynchronously read back the written data.
        fStream.Position = 0;
        asyncResult = fStream.BeginRead(
            tempState.ReadArray, 0 , tempState.ReadArray.Length, 
            new AsyncCallback(EndReadCallback), tempState);

        // Concurrently do other work, such as 
        // logging the write operation.
    }

    // When BeginRead is finished reading data from the file, the 
    // EndReadCallback method is called to end the asynchronous 
    // read operation and then verify the data.
    static void EndReadCallback(IAsyncResult asyncResult)
    {
        State tempState = (State)asyncResult.AsyncState;
        int readCount = tempState.FStream.EndRead(asyncResult);

        int i = 0;
        while(i < readCount)
        {
            if(tempState.ReadArray[i] != tempState.WriteArray[i++])
            {
                Console.WriteLine("Error writing data.");
                tempState.FStream.Close();
                return;
            }
        }
        Console.WriteLine("The data was written to {0} and verified.",
            tempState.FStream.Name);
        tempState.FStream.Close();

        // Signal the main thread that the verification is finished.
        tempState.ManualEvent.Set();
    }

    // Maintain state information to be passed to 
    // EndWriteCallback and EndReadCallback.
    class State
    {
        // fStream is used to read and write to the file.
        FileStream fStream;

        // writeArray stores data that is written to the file.
        byte[] writeArray;

        // readArray stores data that is read from the file.
        byte[] readArray;

        // manualEvent signals the main thread 
        // when verification is complete.
        ManualResetEvent manualEvent;

        public State(FileStream fStream, byte[] writeArray, 
            ManualResetEvent manualEvent)
        {
            this.fStream   = fStream;
            this.writeArray = writeArray;
            this.manualEvent = manualEvent;
            readArray = new byte[writeArray.Length];
        }

        public FileStream FStream
        { get{ return fStream; } }

        public byte[] WriteArray
        { get{ return writeArray; } }

        public byte[] ReadArray
        { get{ return readArray; } }

        public ManualResetEvent ManualEvent
        { get{ return manualEvent; } }
    }
}

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

class FStream
{   
    public static void main(String[] args)
    {
        // Create a synchronization object that gets 
        // signaled when verification is complete.
        ManualResetEvent manualEvent = new ManualResetEvent(false);

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

        FileStream fStream =  new FileStream("Test#@@#.dat", FileMode.Create,
            FileAccess.ReadWrite, FileShare.None, 4096, true);

        // Check that the FileStream was opened asynchronously.
        Console.WriteLine("fStream was {0}opened asynchronously.",
            (fStream.get_IsAsync()) ? "" : "not ");
        FStream classfStream = new FStream();

        // Asynchronously write to the file.
        IAsyncResult asyncResult = fStream.BeginWrite(writeArray, 0,
            writeArray.length, new AsyncCallback(EndWriteCallback),
            classfStream.new State(fStream, writeArray, manualEvent));

        // Concurrently do other work and then wait 
        // for the data to be written and verified.
        manualEvent.WaitOne(5000, false);
    } //main

    // When BeginWrite is finished writing data to the file, the
    // EndWriteCallback method is called to end the asynchronous 
    // write operation and then read back and verify the data.
    static void EndWriteCallback(IAsyncResult asyncResult)
    {
        State tempState = ((State)(asyncResult.get_AsyncState()));
        FileStream fStream = tempState.get_FStream();
        fStream.EndWrite(asyncResult);

        // Asynchronously read back the written data.
        fStream.set_Position(0);
        asyncResult = fStream.BeginRead(tempState.get_ReadArray(), 0,
            tempState.get_ReadArray().length , 
            new AsyncCallback(EndReadCallback), tempState);

        // Concurrently do other work, such as 
        // logging the write operation.
    } //EndWriteCallback

    // When BeginRead is finished reading data from the file, the 
    // EndReadCallback method is called to end the asynchronous 
    // read operation and then verify the data.
    static void EndReadCallback(IAsyncResult asyncResult)
    {
        State tempState = ((State)(asyncResult.get_AsyncState()));
        int readCount = tempState.get_FStream().EndRead(asyncResult);
        int i = 0;
        while((i < readCount)) {
            if ( tempState.get_ReadArray()[i] != 
                    tempState.get_WriteArray()[i++] ) {
                Console.WriteLine("Error writing data.");
                tempState.get_FStream().Close();
                return;
            }
        }
        Console.WriteLine("The data was written to {0} and verified.",
            tempState.get_FStream().get_Name());
        tempState.get_FStream().Close();

        // Signal the main thread that the verification is finished.
        tempState.get_ManualEvent().Set();
    } //EndReadCallback

    // Maintain state information to be passed to 
    // EndWriteCallback and EndReadCallback.
    class State
    {
        // fStream is used to read and write to the file.
        private FileStream fStream;

        // writeArray stores data that is written to the file.
        private ubyte writeArray[];

        // readArray stores data that is read from the file.
        private ubyte readArray[];

        // manualEvent signals the main thread 
        // when verification is complete.
        private ManualResetEvent manualEvent;

        public State(FileStream fStream, ubyte writeArray[],
                    ManualResetEvent manualEvent)
        {
            this.fStream = fStream;
            this.writeArray = writeArray;
            this.manualEvent = manualEvent;
            readArray = new ubyte[writeArray.length ];
        } //State
      
        /** @property 
         */
        public FileStream get_FStream()
        {
            return fStream ;
        }//get_FStream

        /** @property 
         */
        public ubyte[] get_WriteArray()
        {
            return writeArray ;
        }//get_WriteArray

        /** @property 
         */
        public ubyte[] get_ReadArray()
        {
            return readArray;
        }//get_ReadArray

        /** @property 
         */
        public ManualResetEvent get_ManualEvent()
        {
            return manualEvent;
        }//get_ManualEvent
    } //State
} //FStream

Windows 98, Windows 2000 SP4, Windows Millennium, 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