File.OpenWrite(String) Método

Definición

Abre un archivo existente o crea un nuevo archivo para escribir en él.

public:
 static System::IO::FileStream ^ OpenWrite(System::String ^ path);
public static System.IO.FileStream OpenWrite (string path);
static member OpenWrite : string -> System.IO.FileStream
Public Shared Function OpenWrite (path As String) As FileStream

Parámetros

path
String

Archivo que se va a abrir para escritura.

Devoluciones

Objeto FileStream no compartido en la ruta de acceso especificada con acceso Write.

Excepciones

El llamador no dispone del permiso requerido.

o bien

path especifica un archivo de solo lectura o un directorio.

Versiones de .NET Framework y .NET Core anteriores a 2.1: path es una cadena de longitud cero, contiene solo espacios en blanco o contiene uno o varios caracteres no válidos. Puede consultar los caracteres no válidos con el método GetInvalidPathChars().

path es null.

La ruta de acceso especificada, el nombre de archivo o ambos superan la longitud máxima definida por el sistema.

La ruta de acceso especificada no es válida (por ejemplo, está en una unidad no asignada).

path está en un formato no válido.

Ejemplos

En el ejemplo siguiente se abre un archivo para leer y escribir.

using namespace System;
using namespace System::IO;
using namespace System::Text;

int main()
{
   String^ path = "c:\\temp\\MyTest.txt";

   // Open the stream and write to it.
   {
      FileStream^ fs = File::OpenWrite( path );
      try
      {
         array<Byte>^info = (gcnew UTF8Encoding( true ))->
            GetBytes( "This is to test the OpenWrite method." );

         // Add some information to the file.
         fs->Write( info, 0, info->Length );
      }
      finally
      {
         if ( fs )
            delete (IDisposable^)fs;
      }
   }

   // Open the stream and read it back.
   {
      FileStream^ fs = File::OpenRead( path );
      try
      {
         array<Byte>^b = gcnew array<Byte>(1024);
         UTF8Encoding^ temp = gcnew UTF8Encoding( true );
         while ( fs->Read( b, 0, b->Length ) > 0 )
         {
            Console::WriteLine( temp->GetString( b ) );
         }
      }
      finally
      {
         if ( fs )
            delete(IDisposable^)fs;
      }
   }
}
using System;
using System.IO;
using System.Text;

class Test
{
    public static void Main()
    {
        string path = @"c:\temp\MyTest.txt";

        // Open the stream and write to it.
        using (FileStream fs = File.OpenWrite(path))
        {
            Byte[] info =
                new UTF8Encoding(true).GetBytes("This is to test the OpenWrite method.");

            // Add some information to the file.
            fs.Write(info, 0, info.Length);
        }

        // Open the stream and read it back.
        using (FileStream fs = File.OpenRead(path))
        {
            byte[] b = new byte[1024];
            UTF8Encoding temp = new UTF8Encoding(true);

            while (fs.Read(b,0,b.Length) > 0)
            {
                Console.WriteLine(temp.GetString(b));
            }
        }
    }
}
open System.IO
open System.Text

let path = @"c:\temp\MyTest.txt"

// Open the stream and write to it.
do
    use fs = File.OpenWrite path

    let info =
        UTF8Encoding(true)
            .GetBytes "This is to test the OpenWrite method."

    // Add some information to the file.
    fs.Write(info, 0, info.Length)

// Open the stream and read it back.
do
    use fs = File.OpenRead path
    let b = Array.zeroCreate 1024
    let temp = UTF8Encoding true

    while fs.Read(b, 0, b.Length) > 0 do
        printfn $"{temp.GetString b}"
Imports System.IO
Imports System.Text

Public Class Test
  Public Shared Sub Main()
    Dim path As String = "c:\temp\MyTest.txt"

    ' Open the stream and write to it.
    Using fs As FileStream = File.OpenWrite(path)
      Dim info As Byte() = _
       New UTF8Encoding(True).GetBytes("This is to test the OpenWrite method.")

      ' Add some information to the file.
      fs.Write(info, 0, info.Length)
    End Using

    'Open the stream and read it back.
    Using fs As FileStream = File.OpenRead(path)
      Dim b(1023) As Byte
      Dim temp As UTF8Encoding = New UTF8Encoding(True)

      Do While fs.Read(b, 0, b.Length) > 0
        Console.WriteLine(temp.GetString(b))
      Loop
    End Using

  End Sub
End Class

Comentarios

Este método es equivalente a la sobrecarga del constructor con el FileStream(String, FileMode, FileAccess, FileShare) modo de archivo establecido OpenOrCreateen , el acceso establecido Writeen y el modo de recurso compartido establecido en None.

El OpenWrite método abre un archivo si ya existe uno para la ruta de acceso del archivo o crea un nuevo archivo si no existe uno. Para un archivo existente, no anexa el nuevo texto al texto existente. En su lugar, sobrescribe los caracteres existentes con los nuevos caracteres. Si sobrescribe una cadena más larga (por ejemplo, "Se trata de una prueba del método OpenWrite") con una cadena más corta (como "Segunda ejecución"), el archivo contendrá una combinación de las cadenas ("Second runtest of the OpenWrite method").

El path parámetro puede especificar información de ruta de acceso relativa o absoluta. La información de ruta de acceso relativa se interpreta como relativa al directorio de trabajo actual. Para obtener el directorio de trabajo actual, use el GetCurrentDirectory método .

El devuelto FileStream no admite la lectura. Para abrir un archivo para leer y escribir, use Open.

Para obtener una lista de las tareas de E/S comunes, consulte Tareas de E/S comunes.

Se aplica a

Consulte también