StreamWriter Construtores

Definição

Inicializa uma nova instância da classe StreamWriter.Initializes a new instance of the StreamWriter class.

Sobrecargas

StreamWriter(Stream)

Inicializa uma nova instância da classe StreamWriter para o fluxo especificado usando a codificação UTF-8 e o tamanho do buffer padrão.Initializes a new instance of the StreamWriter class for the specified stream by using UTF-8 encoding and the default buffer size.

StreamWriter(String)

Inicializa uma nova instância da classe StreamWriter para o arquivo especificado usando o tamanho do buffer e a codificação padrão.Initializes a new instance of the StreamWriter class for the specified file by using the default encoding and buffer size.

StreamWriter(Stream, Encoding)

Inicializa uma nova instância da classe StreamWriter para o fluxo especificado usando a codificação especificada e o tamanho do buffer padrão.Initializes a new instance of the StreamWriter class for the specified stream by using the specified encoding and the default buffer size.

StreamWriter(String, Boolean)

Inicializa uma nova instância da classe StreamWriter para o arquivo especificado usando o tamanho do buffer e a codificação padrão.Initializes a new instance of the StreamWriter class for the specified file by using the default encoding and buffer size. Se o arquivo existir, ele poderá ser substituído ou dados poderão ser acrescentados a ele.If the file exists, it can be either overwritten or appended to. Se o arquivo não existir, esse construtor criará um novo arquivo.If the file does not exist, this constructor creates a new file.

StreamWriter(Stream, Encoding, Int32)

Inicializa uma nova instância da classe StreamWriter para o fluxo especificado usando o tamanho do buffer e a codificação especificados.Initializes a new instance of the StreamWriter class for the specified stream by using the specified encoding and buffer size.

StreamWriter(String, Boolean, Encoding)

Inicializa uma nova instância da classe StreamWriter para o arquivo especificado usando a codificação especificada e o tamanho do buffer padrão.Initializes a new instance of the StreamWriter class for the specified file by using the specified encoding and default buffer size. Se o arquivo existir, ele poderá ser substituído ou dados poderão ser acrescentados a ele.If the file exists, it can be either overwritten or appended to. Se o arquivo não existir, esse construtor criará um novo arquivo.If the file does not exist, this constructor creates a new file.

StreamWriter(Stream, Encoding, Int32, Boolean)

Inicializa uma nova instância da classe StreamWriter para o fluxo especificado usando o tamanho do buffer e a codificação especificados e opcionalmente deixa o fluxo aberto.Initializes a new instance of the StreamWriter class for the specified stream by using the specified encoding and buffer size, and optionally leaves the stream open.

StreamWriter(String, Boolean, Encoding, Int32)

Inicializa uma nova instância da classe StreamWriter para o arquivo especificado no caminho especificado usando a codificação especificada e o tamanho do buffer.Initializes a new instance of the StreamWriter class for the specified file on the specified path, using the specified encoding and buffer size. Se o arquivo existir, ele poderá ser substituído ou dados poderão ser acrescentados a ele.If the file exists, it can be either overwritten or appended to. Se o arquivo não existir, esse construtor criará um novo arquivo.If the file does not exist, this constructor creates a new file.

StreamWriter(Stream)

Inicializa uma nova instância da classe StreamWriter para o fluxo especificado usando a codificação UTF-8 e o tamanho do buffer padrão.Initializes a new instance of the StreamWriter class for the specified stream by using UTF-8 encoding and the default buffer size.

public:
 StreamWriter(System::IO::Stream ^ stream);
public StreamWriter (System.IO.Stream stream);
new System.IO.StreamWriter : System.IO.Stream -> System.IO.StreamWriter
Public Sub New (stream As Stream)

Parâmetros

stream
Stream

O fluxo para gravação.The stream to write to.

Exceções

stream não é gravável.stream is not writable.

stream é null.stream is null.

Exemplos

O exemplo de código a seguir demonstra esse construtor.The following code example demonstrates this constructor.

using System;
using System.IO;

namespace ConsoleApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            string fileName = "test.txt";
            string textToAdd = "Example text in file";
            FileStream fs = null;
            try
            {
                fs = new FileStream(fileName, FileMode.CreateNew);
                using (StreamWriter writer = new StreamWriter(fs))
                {
                    writer.Write(textToAdd);
                }
            }
            finally
            {
                if (fs != null)
                    fs.Dispose();
            }
        }
    }
}
Imports System.IO

Module Module1

    Sub Main()
        Dim fileName As String = "test.txt"
        Dim textToAdd As String = "Example text in file"
        Dim fs As FileStream = Nothing
        Try
            fs = New FileStream(fileName, FileMode.CreateNew)
            Using writer As StreamWriter = New StreamWriter(fs)
                writer.Write(textToAdd)
            End Using
        Finally
            If Not fs Is Nothing Then
                fs.Dispose()
            End If
        End Try
    End Sub

End Module

Comentários

Esse construtor cria uma StreamWriter codificação com UTF-8 sem uma marca de Byte-Order (bom), portanto, seu GetPreamble método retorna uma matriz de bytes vazia.This constructor creates a StreamWriter with UTF-8 encoding without a Byte-Order Mark (BOM), so its GetPreamble method returns an empty byte array. A codificação UTF-8 padrão para esse construtor gera uma exceção em bytes inválidos.The default UTF-8 encoding for this constructor throws an exception on invalid bytes. Esse comportamento é diferente do comportamento fornecido pelo objeto de codificação na Encoding.UTF8 propriedade.This behavior is different from the behavior provided by the encoding object in the Encoding.UTF8 property. Para especificar se uma exceção é lançada em bytes inválidos, use um construtor que aceite um objeto de codificação como um parâmetro, como StreamWriter .To specify whether an exception is thrown on invalid bytes, use a constructor that accepts an encoding object as a parameter, such as StreamWriter. A BaseStream propriedade é inicializada usando o stream parâmetro.The BaseStream property is initialized using the stream parameter. A posição do fluxo não é redefinida.The position of the stream is not reset.

O StreamWriter objeto chama Dispose() o objeto fornecido Stream quando StreamWriter.Dispose é chamado.The StreamWriter object calls Dispose() on the provided Stream object when StreamWriter.Dispose is called.

Cuidado

Quando você compila um conjunto de caracteres com uma configuração cultural específica e recupera os mesmos caracteres com uma configuração cultural diferente, os caracteres talvez não sejam interpretáveis e poderiam causar uma exceção a ser lançada.When you compile a set of characters with a particular cultural setting and retrieve those same characters with a different cultural setting, the characters might not be interpretable and could cause an exception to be thrown.

Para obter uma lista de tarefas comuns de e/s, consulte tarefas comuns de e/s.For a list of common I/O tasks, see Common I/O Tasks.

Aplica-se a

StreamWriter(String)

Inicializa uma nova instância da classe StreamWriter para o arquivo especificado usando o tamanho do buffer e a codificação padrão.Initializes a new instance of the StreamWriter class for the specified file by using the default encoding and buffer size.

public:
 StreamWriter(System::String ^ path);
public StreamWriter (string path);
new System.IO.StreamWriter : string -> System.IO.StreamWriter
Public Sub New (path As String)

Parâmetros

path
String

O caminho de arquivo completo no qual gravar.The complete file path to write to. path pode ser um nome de arquivo.path can be a file name.

Exceções

Acesso negado.Access is denied.

path é uma cadeia de caracteres vazia ("").path is an empty string ("").

- ou --or- path contém o nome de um dispositivo de sistema (com1, com2 e assim por diante).path contains the name of a system device (com1, com2, and so on).

path é null.path is null.

O caminho especificado é inválido (por exemplo, ele está em uma unidade não mapeada).The specified path is invalid (for example, it is on an unmapped drive).

O caminho especificado, o nome de arquivo, ou ambos excedem o tamanho máximo definido pelo sistema.The specified path, file name, or both exceed the system-defined maximum length.

path inclui uma sintaxe incorreta ou inválida para o nome do arquivo, o nome do diretório ou a sintaxe de rótulo do volume.path includes an incorrect or invalid syntax for file name, directory name, or volume label syntax.

O chamador não tem a permissão necessária.The caller does not have the required permission.

Exemplos

O exemplo de código a seguir demonstra esse construtor.The following code example demonstrates this constructor.

using System;
using System.IO;
using System.Text;

namespace ConsoleApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            string fileName = "test.txt";
            string textToAdd = "Example text in file";

            using (StreamWriter writer = new StreamWriter(fileName))
            {
                writer.Write(textToAdd);
            }
        }
    }
}
Imports System.IO
Imports System.Text

Module Module1

    Sub Main()
        Dim fileName As String = "test.txt"
        Dim textToAdd As String = "Example text in file"

        Using writer As StreamWriter = New StreamWriter(fileName)
            writer.Write(textToAdd)
        End Using
    End Sub

End Module

Comentários

Esse construtor cria uma StreamWriter codificação com UTF-8 sem uma marca de Byte-Order (bom), portanto, seu GetPreamble método retorna uma matriz de bytes vazia.This constructor creates a StreamWriter with UTF-8 encoding without a Byte-Order Mark (BOM), so its GetPreamble method returns an empty byte array. A codificação UTF-8 padrão para esse construtor gera uma exceção em bytes inválidos.The default UTF-8 encoding for this constructor throws an exception on invalid bytes. Esse comportamento é diferente do comportamento fornecido pelo objeto de codificação na Encoding.UTF8 propriedade.This behavior is different from the behavior provided by the encoding object in the Encoding.UTF8 property. Para especificar uma BOM e determinar se uma exceção é lançada em bytes inválidos, use um construtor que aceite um objeto de codificação como um parâmetro, como StreamWriter(String, Boolean, Encoding) .To specify a BOM and determine whether an exception is thrown on invalid bytes, use a constructor that accepts an encoding object as a parameter, such as StreamWriter(String, Boolean, Encoding).

O path parâmetro pode ser um nome de arquivo, incluindo um arquivo em um compartilhamento UNC (Convenção de nomenclatura universal).The path parameter can be a file name, including a file on a Universal Naming Convention (UNC) share. Se o arquivo existir, ele será substituído; caso contrário, um novo arquivo será criado.If the file exists, it is overwritten; otherwise, a new file is created.

pathNão é necessário que o parâmetro seja um arquivo armazenado em disco; ele pode ser qualquer parte de um sistema que ofereça suporte ao acesso usando fluxos.The path parameter is not required to be a file stored on disk; it can be any part of a system that supports access using streams.

Cuidado

Quando você compila um conjunto de caracteres com uma configuração cultural específica e recupera os mesmos caracteres com uma configuração cultural diferente, os caracteres talvez não sejam interpretáveis e poderiam causar uma exceção a ser lançada.When you compile a set of characters with a particular cultural setting and retrieve those same characters with a different cultural setting, the characters might not be interpretable and could cause an exception to be thrown.

Para obter uma lista de tarefas comuns de e/s, consulte tarefas comuns de e/s.For a list of common I/O tasks, see Common I/O Tasks.

Aplica-se a

StreamWriter(Stream, Encoding)

Inicializa uma nova instância da classe StreamWriter para o fluxo especificado usando a codificação especificada e o tamanho do buffer padrão.Initializes a new instance of the StreamWriter class for the specified stream by using the specified encoding and the default buffer size.

public:
 StreamWriter(System::IO::Stream ^ stream, System::Text::Encoding ^ encoding);
public StreamWriter (System.IO.Stream stream, System.Text.Encoding encoding);
new System.IO.StreamWriter : System.IO.Stream * System.Text.Encoding -> System.IO.StreamWriter
Public Sub New (stream As Stream, encoding As Encoding)

Parâmetros

stream
Stream

O fluxo para gravação.The stream to write to.

encoding
Encoding

A codificação de caracteres a ser usada.The character encoding to use.

Exceções

stream ou encoding é null.stream or encoding is null.

stream não é gravável.stream is not writable.

Exemplos

O exemplo a seguir demonstra esse construtor.The following example demonstrates this constructor.

using System;
using System.IO;
using System.Text;

namespace ConsoleApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            string fileName = "test.txt";
            string textToAdd = "Example text in file";
            FileStream fs = null;
            try
            {
               fs = new FileStream(fileName, FileMode.CreateNew);
               using (StreamWriter writer = new StreamWriter(fs, Encoding.Default))
                {
                    writer.Write(textToAdd);
                }
            }
            finally
            {
                if (fs != null)
                    fs.Dispose();
            }
        }
    }
}
Imports System.IO
Imports System.Text

Module Module1

    Sub Main()
        Dim fileName As String = "test.txt"
        Dim textToAdd As String = "Example text in file"
        Dim fs As FileStream = Nothing
        Try
            fs = New FileStream(fileName, FileMode.CreateNew)
            Using writer As StreamWriter = New StreamWriter(fs, Encoding.Default)
                writer.Write(textToAdd)
            End Using
        Finally
            If Not fs Is Nothing Then
                fs.Dispose()
            End If
        End Try
    End Sub

End Module

Comentários

Esse construtor inicializa a Encoding propriedade usando o parâmetro Encoding e a BaseStream propriedade usando o parâmetro Stream.This constructor initializes the Encoding property using the encoding parameter, and the BaseStream property using the stream parameter. A posição do fluxo não é redefinida.The position of the stream is not reset. Para obter mais informações, consulte: Encoding.For additional information, see Encoding.

O StreamWriter objeto chama Dispose() o objeto fornecido Stream quando StreamWriter.Dispose é chamado.The StreamWriter object calls Dispose() on the provided Stream object when StreamWriter.Dispose is called.

Cuidado

Quando você compila um conjunto de caracteres com uma configuração cultural específica e recupera os mesmos caracteres com uma configuração cultural diferente, os caracteres podem não ser interpretáveis e podem causar a geração de uma exceção.When you compile a set of characters with a particular cultural setting and retrieve those same characters with a different cultural setting, the characters might not be interpretable, and could cause an exception to be thrown.

Para obter uma lista de tarefas comuns de e/s, consulte tarefas comuns de e/s.For a list of common I/O tasks, see Common I/O Tasks.

Confira também

Aplica-se a

StreamWriter(String, Boolean)

Inicializa uma nova instância da classe StreamWriter para o arquivo especificado usando o tamanho do buffer e a codificação padrão.Initializes a new instance of the StreamWriter class for the specified file by using the default encoding and buffer size. Se o arquivo existir, ele poderá ser substituído ou dados poderão ser acrescentados a ele.If the file exists, it can be either overwritten or appended to. Se o arquivo não existir, esse construtor criará um novo arquivo.If the file does not exist, this constructor creates a new file.

public:
 StreamWriter(System::String ^ path, bool append);
public StreamWriter (string path, bool append);
new System.IO.StreamWriter : string * bool -> System.IO.StreamWriter
Public Sub New (path As String, append As Boolean)

Parâmetros

path
String

O caminho de arquivo completo no qual gravar.The complete file path to write to.

append
Boolean

true para acrescentar dados ao arquivo; false para substituir o arquivo.true to append data to the file; false to overwrite the file. Se o arquivo especificado não existir, esse parâmetro não terá efeito e o construtor criará um novo arquivo.If the specified file does not exist, this parameter has no effect, and the constructor creates a new file.

Exceções

Acesso negado.Access is denied.

path está vazio.path is empty.

- ou --or- path contém o nome de um dispositivo de sistema (com1, com2 e assim por diante).path contains the name of a system device (com1, com2, and so on).

path é null.path is null.

O caminho especificado é inválido (por exemplo, ele está em uma unidade não mapeada).The specified path is invalid (for example, it is on an unmapped drive).

path inclui uma sintaxe incorreta ou inválida para o nome do arquivo, o nome do diretório ou a sintaxe de rótulo do volume.path includes an incorrect or invalid syntax for file name, directory name, or volume label syntax.

O caminho especificado, o nome de arquivo, ou ambos excedem o tamanho máximo definido pelo sistema.The specified path, file name, or both exceed the system-defined maximum length.

O chamador não tem a permissão necessária.The caller does not have the required permission.

Exemplos

O exemplo de código a seguir demonstra esse construtor.The following code example demonstrates this constructor.

using System;
using System.IO;
using System.Text;

namespace ConsoleApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            string fileName = "test.txt";
            string textToAdd = "Example text in file";

            using (StreamWriter writer = new StreamWriter(fileName, true))
            {
                writer.Write(textToAdd);
            }
        }
    }
}
Imports System.IO
Imports System.Text

Module Module1

    Sub Main()
        Dim fileName As String = "test.txt"
        Dim textToAdd As String = "Example text in file"

        Using writer As StreamWriter = New StreamWriter(fileName, True)
            writer.Write(textToAdd)
        End Using
    End Sub

End Module

Comentários

Esse construtor cria uma StreamWriter codificação com UTF-8 sem uma marca de Byte-Order (bom), portanto, seu GetPreamble método retorna uma matriz de bytes vazia.This constructor creates a StreamWriter with UTF-8 encoding without a Byte-Order Mark (BOM), so its GetPreamble method returns an empty byte array. A codificação UTF-8 padrão para esse construtor gera uma exceção em bytes inválidos.The default UTF-8 encoding for this constructor throws an exception on invalid bytes. Esse comportamento é diferente do comportamento fornecido pelo objeto de codificação na Encoding.UTF8 propriedade.This behavior is different from the behavior provided by the encoding object in the Encoding.UTF8 property. Para especificar uma BOM e determinar se uma exceção é lançada em bytes inválidos, use um construtor que aceite um objeto de codificação como um parâmetro, como StreamWriter(String, Boolean, Encoding) .To specify a BOM and determine whether an exception is thrown on invalid bytes, use a constructor that accepts an encoding object as a parameter, such as StreamWriter(String, Boolean, Encoding).

O path parâmetro pode ser um nome de arquivo, incluindo um arquivo em um compartilhamento UNC (Convenção de nomenclatura universal).The path parameter can be a file name, including a file on a Universal Naming Convention (UNC) share.

pathNão é necessário que o parâmetro seja um arquivo armazenado em disco; ele pode ser qualquer parte de um sistema que ofereça suporte ao acesso usando fluxos.The path parameter is not required to be a file stored on disk; it can be any part of a system that supports access using streams.

Cuidado

Quando você compila um conjunto de caracteres com uma configuração cultural específica e recupera os mesmos caracteres com uma configuração cultural diferente, os caracteres podem não ser interpretáveis e podem causar a geração de uma exceção.When you compile a set of characters with a particular cultural setting and retrieve those same characters with a different cultural setting, the characters might not be interpretable, and could cause an exception to be thrown.

Para obter uma lista de tarefas comuns de e/s, consulte tarefas comuns de e/s.For a list of common I/O tasks, see Common I/O Tasks.

Aplica-se a

StreamWriter(Stream, Encoding, Int32)

Inicializa uma nova instância da classe StreamWriter para o fluxo especificado usando o tamanho do buffer e a codificação especificados.Initializes a new instance of the StreamWriter class for the specified stream by using the specified encoding and buffer size.

public:
 StreamWriter(System::IO::Stream ^ stream, System::Text::Encoding ^ encoding, int bufferSize);
public StreamWriter (System.IO.Stream stream, System.Text.Encoding encoding, int bufferSize);
new System.IO.StreamWriter : System.IO.Stream * System.Text.Encoding * int -> System.IO.StreamWriter
Public Sub New (stream As Stream, encoding As Encoding, bufferSize As Integer)

Parâmetros

stream
Stream

O fluxo para gravação.The stream to write to.

encoding
Encoding

A codificação de caracteres a ser usada.The character encoding to use.

bufferSize
Int32

O tamanho do buffer, em bytes.The buffer size, in bytes.

Exceções

stream ou encoding é null.stream or encoding is null.

bufferSize é negativo.bufferSize is negative.

stream não é gravável.stream is not writable.

Exemplos

O exemplo a seguir demonstra esse construtor.The following example demonstrates this constructor.

using System;
using System.IO;
using System.Text;

namespace ConsoleApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            string fileName = "test.txt";
            string textToAdd = "Example text in file";
            FileStream fs = null;
            try
            {
                fs = new FileStream(fileName, FileMode.CreateNew);
                using (StreamWriter writer = new StreamWriter(fs, Encoding.UTF8, 512))
                {
                    writer.Write(textToAdd);
                }
            }
            finally
            {
                if (fs != null)
                    fs.Dispose();
            }
        }
    }
}
Imports System.IO
Imports System.Text

Module Module1

    Sub Main()
        Dim fileName As String = "test.txt"
        Dim textToAdd As String = "Example text in file"
        Dim fs As FileStream = Nothing
        Try
            fs = New FileStream(fileName, FileMode.CreateNew)
            Using writer As StreamWriter = New StreamWriter(fs, Encoding.Default, 512)
                writer.Write(textToAdd)
            End Using
        Finally
            If Not fs Is Nothing Then
                fs.Dispose()
            End If
        End Try
    End Sub

End Module

Comentários

Esse construtor inicializa a Encoding propriedade usando o encoding parâmetro e a BaseStream propriedade usando o stream parâmetro.This constructor initializes the Encoding property using the encoding parameter, and the BaseStream property using the stream parameter. A posição do fluxo não é redefinida.The position of the stream is not reset. Para obter mais informações, consulte: Encoding.For additional information, see Encoding.

O StreamWriter objeto chama Dispose() o objeto fornecido Stream quando StreamWriter.Dispose é chamado.The StreamWriter object calls Dispose() on the provided Stream object when StreamWriter.Dispose is called.

Cuidado

Quando você compila um conjunto de caracteres com uma configuração cultural específica e recupera os mesmos caracteres com uma configuração cultural diferente, os caracteres podem não ser interpretáveis e podem causar a geração de uma exceção.When you compile a set of characters with a particular cultural setting and retrieve those same characters with a different cultural setting, the characters might not be interpretable, and could cause an exception to be thrown.

Para obter uma lista de tarefas comuns de e/s, consulte tarefas comuns de e/s.For a list of common I/O tasks, see Common I/O Tasks.

Confira também

Aplica-se a

StreamWriter(String, Boolean, Encoding)

Inicializa uma nova instância da classe StreamWriter para o arquivo especificado usando a codificação especificada e o tamanho do buffer padrão.Initializes a new instance of the StreamWriter class for the specified file by using the specified encoding and default buffer size. Se o arquivo existir, ele poderá ser substituído ou dados poderão ser acrescentados a ele.If the file exists, it can be either overwritten or appended to. Se o arquivo não existir, esse construtor criará um novo arquivo.If the file does not exist, this constructor creates a new file.

public:
 StreamWriter(System::String ^ path, bool append, System::Text::Encoding ^ encoding);
public StreamWriter (string path, bool append, System.Text.Encoding encoding);
new System.IO.StreamWriter : string * bool * System.Text.Encoding -> System.IO.StreamWriter
Public Sub New (path As String, append As Boolean, encoding As Encoding)

Parâmetros

path
String

O caminho de arquivo completo no qual gravar.The complete file path to write to.

append
Boolean

true para acrescentar dados ao arquivo; false para substituir o arquivo.true to append data to the file; false to overwrite the file. Se o arquivo especificado não existir, esse parâmetro não terá efeito e o construtor criará um novo arquivo.If the specified file does not exist, this parameter has no effect, and the constructor creates a new file.

encoding
Encoding

A codificação de caracteres a ser usada.The character encoding to use.

Exceções

Acesso negado.Access is denied.

path está vazio.path is empty.

- ou --or- path contém o nome de um dispositivo de sistema (com1, com2 e assim por diante).path contains the name of a system device (com1, com2, and so on).

path é null.path is null.

O caminho especificado é inválido (por exemplo, ele está em uma unidade não mapeada).The specified path is invalid (for example, it is on an unmapped drive).

path inclui uma sintaxe incorreta ou inválida para o nome do arquivo, o nome do diretório ou a sintaxe de rótulo do volume.path includes an incorrect or invalid syntax for file name, directory name, or volume label syntax.

O caminho especificado, o nome de arquivo, ou ambos excedem o tamanho máximo definido pelo sistema.The specified path, file name, or both exceed the system-defined maximum length.

O chamador não tem a permissão necessária.The caller does not have the required permission.

Exemplos

O exemplo a seguir demonstra esse construtor.The following example demonstrates this constructor.

using System;
using System.IO;
using System.Text;

namespace ConsoleApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            string fileName = "test.txt";
            string textToAdd = "Example text in file";

            using (StreamWriter writer = new StreamWriter(fileName, true, Encoding.UTF8))
            {
                writer.Write(textToAdd);
            }
        }
    }
}
Imports System.IO
Imports System.Text

Module Module1

    Sub Main()
        Dim fileName As String = "test.txt"
        Dim textToAdd As String = "Example text in file"

        Using writer As StreamWriter = New StreamWriter(fileName, True, Encoding.UTF8)
            writer.Write(textToAdd)
        End Using
    End Sub

End Module

Comentários

Esse construtor inicializa a Encoding propriedade usando o parâmetro Encoding.This constructor initializes the Encoding property using the encoding parameter. Para obter mais informações, consulte: Encoding.For additional information, see Encoding.

path pode ser um nome de arquivo, incluindo um arquivo em um compartilhamento UNC (Convenção de nomenclatura universal).path can be a file name, including a file on a Universal Naming Convention (UNC) share.

path Não é necessário para ser um arquivo armazenado em disco; Ele pode ser qualquer parte de um sistema que dá suporte ao acesso via fluxos.path is not required to be a file stored on disk; it can be any part of a system that supports access via streams.

Cuidado

Quando você compila um conjunto de caracteres com uma configuração cultural específica e recupera os mesmos caracteres com uma configuração cultural diferente, os caracteres podem não ser interpretáveis e podem causar a geração de uma exceção.When you compile a set of characters with a particular cultural setting and retrieve those same characters with a different cultural setting, the characters might not be interpretable, and could cause an exception to be thrown.

Para obter uma lista de tarefas comuns de e/s, consulte tarefas comuns de e/s.For a list of common I/O tasks, see Common I/O Tasks.

Confira também

Aplica-se a

StreamWriter(Stream, Encoding, Int32, Boolean)

Inicializa uma nova instância da classe StreamWriter para o fluxo especificado usando o tamanho do buffer e a codificação especificados e opcionalmente deixa o fluxo aberto.Initializes a new instance of the StreamWriter class for the specified stream by using the specified encoding and buffer size, and optionally leaves the stream open.

public:
 StreamWriter(System::IO::Stream ^ stream, System::Text::Encoding ^ encoding, int bufferSize, bool leaveOpen);
public StreamWriter (System.IO.Stream stream, System.Text.Encoding encoding, int bufferSize, bool leaveOpen);
public StreamWriter (System.IO.Stream stream, System.Text.Encoding? encoding = default, int bufferSize = -1, bool leaveOpen = false);
new System.IO.StreamWriter : System.IO.Stream * System.Text.Encoding * int * bool -> System.IO.StreamWriter
Public Sub New (stream As Stream, encoding As Encoding, bufferSize As Integer, leaveOpen As Boolean)
Public Sub New (stream As Stream, Optional encoding As Encoding = Nothing, Optional bufferSize As Integer = -1, Optional leaveOpen As Boolean = false)

Parâmetros

stream
Stream

O fluxo para gravação.The stream to write to.

encoding
Encoding

A codificação de caracteres a ser usada.The character encoding to use.

bufferSize
Int32

O tamanho do buffer, em bytes.The buffer size, in bytes.

leaveOpen
Boolean

true para deixar o fluxo aberto após o objeto StreamWriter ser descartado; caso contrário, false.true to leave the stream open after the StreamWriter object is disposed; otherwise, false.

Exceções

stream ou encoding é null.stream or encoding is null.

bufferSize é negativo.bufferSize is negative.

stream não é gravável.stream is not writable.

Exemplos

O exemplo a seguir demonstra esse construtor.The following example demonstrates this constructor.

using System;
using System.IO;
using System.Text;

namespace ConsoleApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            string fileName = "test.txt";
            string textToAdd = "Example text in file";
            FileStream fs = null;
            try
            {
                fs = new FileStream(fileName, FileMode.CreateNew);
                using (StreamWriter writer = new StreamWriter(fs, Encoding.UTF8, 512, false))
                {
                    writer.Write(textToAdd);
                }
            }
            finally
            {
                if (fs != null)
                    fs.Dispose();
            }
        }
    }
}
Imports System.IO
Imports System.Text

Module Module1

    Sub Main()
        Dim fileName As String = "test.txt"
        Dim textToAdd As String = "Example text in file"
        Dim fs As FileStream = Nothing
        Try
            fs = New FileStream(fileName, FileMode.CreateNew)
            Using writer As StreamWriter = New StreamWriter(fs, Encoding.Default, 512, False)
                writer.Write(textToAdd)
            End Using
        Finally
            If Not fs Is Nothing Then
                fs.Dispose()
            End If
        End Try
    End Sub

End Module

Comentários

A menos que você defina o leaveOpen parâmetro como true , o StreamWriter objeto chama Dispose() o Stream objeto fornecido quando StreamWriter.Dispose é chamado.Unless you set the leaveOpen parameter to true, the StreamWriter object calls Dispose() on the provided Stream object when StreamWriter.Dispose is called.

Esse construtor inicializa a Encoding propriedade usando o encoding parâmetro e inicializa a BaseStream propriedade usando o stream parâmetro.This constructor initializes the Encoding property by using the encoding parameter, and initializes the BaseStream property by using the stream parameter. A posição do fluxo não é redefinida.The position of the stream is not reset. Para obter informações adicionais, consulte a Encoding propriedade.For additional information, see the Encoding property.

Cuidado

Quando você compila um conjunto de caracteres com uma configuração cultural específica e recupera os mesmos caracteres com uma configuração cultural diferente, os caracteres podem não ser interpretáveis e podem causar a geração de uma exceção.When you compile a set of characters with a particular cultural setting and retrieve those same characters with a different cultural setting, the characters might not be interpretable, and could cause an exception to be thrown.

Aplica-se a

StreamWriter(String, Boolean, Encoding, Int32)

Inicializa uma nova instância da classe StreamWriter para o arquivo especificado no caminho especificado usando a codificação especificada e o tamanho do buffer.Initializes a new instance of the StreamWriter class for the specified file on the specified path, using the specified encoding and buffer size. Se o arquivo existir, ele poderá ser substituído ou dados poderão ser acrescentados a ele.If the file exists, it can be either overwritten or appended to. Se o arquivo não existir, esse construtor criará um novo arquivo.If the file does not exist, this constructor creates a new file.

public:
 StreamWriter(System::String ^ path, bool append, System::Text::Encoding ^ encoding, int bufferSize);
public StreamWriter (string path, bool append, System.Text.Encoding encoding, int bufferSize);
new System.IO.StreamWriter : string * bool * System.Text.Encoding * int -> System.IO.StreamWriter
Public Sub New (path As String, append As Boolean, encoding As Encoding, bufferSize As Integer)

Parâmetros

path
String

O caminho de arquivo completo no qual gravar.The complete file path to write to.

append
Boolean

true para acrescentar dados ao arquivo; false para substituir o arquivo.true to append data to the file; false to overwrite the file. Se o arquivo especificado não existir, esse parâmetro não terá efeito e o construtor criará um novo arquivo.If the specified file does not exist, this parameter has no effect, and the constructor creates a new file.

encoding
Encoding

A codificação de caracteres a ser usada.The character encoding to use.

bufferSize
Int32

O tamanho do buffer, em bytes.The buffer size, in bytes.

Exceções

path é uma cadeia de caracteres vazia ("").path is an empty string ("").

- ou --or- path contém o nome de um dispositivo de sistema (com1, com2 e assim por diante).path contains the name of a system device (com1, com2, and so on).

path ou encoding é null.path or encoding is null.

bufferSize é negativo.bufferSize is negative.

path inclui uma sintaxe incorreta ou inválida para o nome do arquivo, o nome do diretório ou a sintaxe de rótulo do volume.path includes an incorrect or invalid syntax for file name, directory name, or volume label syntax.

O chamador não tem a permissão necessária.The caller does not have the required permission.

Acesso negado.Access is denied.

O caminho especificado é inválido (por exemplo, ele está em uma unidade não mapeada).The specified path is invalid (for example, it is on an unmapped drive).

O caminho especificado, o nome de arquivo, ou ambos excedem o tamanho máximo definido pelo sistema.The specified path, file name, or both exceed the system-defined maximum length.

Exemplos

O exemplo a seguir demonstra esse construtor.The following example demonstrates this constructor.

using System;
using System.IO;
using System.Text;

namespace ConsoleApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            string fileName = "test.txt";
            string textToAdd = "Example text in file";

            using (StreamWriter writer = new StreamWriter(fileName, true, Encoding.UTF8, 512))
            {
                writer.Write(textToAdd);
            }
        }
    }
}
Imports System.IO
Imports System.Text

Module Module1

    Sub Main()
        Dim fileName As String = "test.txt"
        Dim textToAdd As String = "Example text in file"

        Using writer As StreamWriter = New StreamWriter(fileName, True, Encoding.UTF8, 512)
            writer.Write(textToAdd)
        End Using
    End Sub

End Module

Comentários

Esse construtor inicializa a Encoding propriedade usando o parâmetro Encoding.This constructor initializes the Encoding property using the encoding parameter. Para obter mais informações, consulte: Encoding.For additional information, see Encoding.

path pode ser um nome de arquivo, incluindo um arquivo em um compartilhamento UNC (Convenção de nomenclatura universal).path can be a file name, including a file on a Universal Naming Convention (UNC) share.

path Não é necessário para ser um arquivo armazenado em disco; Ele pode ser qualquer parte de um sistema que dá suporte ao acesso via fluxos.path is not required to be a file stored on disk; it can be any part of a system that supports access via streams.

Cuidado

Quando você compila um conjunto de caracteres com uma configuração cultural específica e recupera os mesmos caracteres com uma configuração cultural diferente, os caracteres podem não ser interpretáveis e podem causar a geração de uma exceção.When you compile a set of characters with a particular cultural setting and retrieve those same characters with a different cultural setting, the characters might not be interpretable, and could cause an exception to be thrown.

Para obter uma lista de tarefas comuns de e/s, consulte tarefas comuns de e/s.For a list of common I/O tasks, see Common I/O Tasks.

Confira também

Aplica-se a