FileSystem.Write(Int32, Object[]) Método
Definição
Grava dados em um arquivo sequencial.Writes data to a sequential file. Dados gravados com Write costumam ser lidos a partir de um arquivo usando Input.Data written with Write is usually read from a file by using Input.
public:
static void Write(int FileNumber, ... cli::array <System::Object ^> ^ Output);
public static void Write (int FileNumber, params object[] Output);
static member Write : int * obj[] -> unit
Public Sub Write (FileNumber As Integer, ParamArray Output As Object())
Parâmetros
- FileNumber
- Int32
Obrigatórios.Required. Uma expressão Integer que contém qualquer número de arquivo válido.An Integer expression that contains any valid file number.
- Output
- Object[]
Opcional.Optional. Uma ou mais expressões delimitadas por vírgula para gravar em um arquivo.One or more comma-delimited expressions to write to a file.
Exceções
O modo de arquivo é inválido.File mode is invalid.
Exemplos
Este exemplo usa a Write função para gravar dados brutos em um arquivo sequencial.This example uses the Write function to write raw data to a sequential file.
' Open file for output.
FileOpen(1, "TestFile.txt", OpenMode.Output)
' Print text to the file. The quotation marks will be in the display.
Write(1, "This is a test.")
' Go to the next line.
WriteLine(1)
' Skip a line.
WriteLine(1)
' Print in two print zones. You will see commas and quotation marks
' in the output file.
WriteLine(1, "Zone 1", SPC(10), "Zone 2")
' Build a longer string before calling WriteLine.
WriteLine(1, "Hello" & " " & "World")
' Include five leading spaces.
WriteLine(1, SPC(5), "Leading spaces")
' Print a word starting at column 10.
WriteLine(1, TAB(10), "Hello")
' Assign Boolean and Date values.
Dim aBool As Boolean
Dim aDate As DateTime
aBool = False
aDate = DateTime.Parse("February 12, 1969")
' Dates and Booleans are translated using locale settings of
' your system.
WriteLine(1, aBool & " is a Boolean value.")
WriteLine(1, aDate & " is a date.")
' Close the file.
FileClose(1)
' Contents of TestFile.txt
'"This is a test.",
'
'"Zone 1", "Zone 2"
'"Hello World"
' "Leading spaces"
' ,"Hello"
'"False is a Boolean value."
'"2/12/1969 is a date."
Comentários
As Write WriteLine funções e são fornecidas para compatibilidade com versões anteriores e podem afetar o desempenho.The Write and WriteLine functions are provided for backward compatibility and may affect performance. Para aplicativos não herdados, o My.Computer.FileSystem objeto fornece melhor desempenho.For non-legacy applications, the My.Computer.FileSystem object provides better performance. Para obter mais informações, consulte acesso a arquivos com Visual Basic.For more information, see File Access with Visual Basic.
Se você omitir Output , uma linha em branco será impressa no arquivo.If you omit Output, a blank line is printed to the file. Várias expressões podem ser separadas com uma vírgula.Multiple expressions can be separated with a comma.
Ao contrário da Print função, a Write função insere vírgulas entre itens e aspas ao contrário de cadeias de caracteres conforme elas são gravadas no arquivo.Unlike the Print function, the Write function inserts commas between items and quotation marks around strings as they are written to the file. Você não precisa colocar delimitadores explícitos na lista.You do not have to put explicit delimiters in the list. Quando Write é usado para gravar dados em um arquivo, somente os formatos numéricos, Boolean Date, NULL e Error data têm suporte.When Write is used to write data to a file, only numeric, Boolean, date, null, and Error data formats are supported. As suposições universais a seguir são seguidas para que os dados sempre possam ser lidos e interpretados corretamente usando Input , independentemente da localidade:The following universal assumptions are followed so the data can always be read and correctly interpreted using Input, regardless of locale:
Os dados numéricos são sempre gravados usando o ponto como separador decimal.Numeric data is always written using the period as the decimal separator.
Para
Booleandados,#TRUE#ou#FALSE#é impresso.ForBooleandata, either#TRUE#or#FALSE#is printed. AsTrueFalsepalavras-chave e não são convertidas, independentemente da localidade.TheTrueandFalsekeywords are not translated, regardless of locale.Os dados de data são gravados no arquivo usando o formato de data universal.Date data is written to the file using the universal date format. Quando o componente data ou hora está ausente ou zero, apenas a parte fornecida é gravada no arquivo.When either the date or the time component is missing or zero, only the part provided is written to the file.
Nada será gravado no arquivo se
Outputos dados estiverem vazios.Nothing is written to the file ifOutputdata is empty. No entanto, para dados nulos,#NULL#é gravado.However, for null data,#NULL#is written.Para
Errordados, a saída aparece como#ERROR errorcode#.ForErrordata, the output appears as#ERROR errorcode#. AErrorpalavra-chave não é traduzida, independentemente da localidade.TheErrorkeyword is not translated, regardless of locale.
WriteLine Insere um caractere de nova linha (ou seja, um retorno de carro/alimentação de linha ou Chr(13) + Chr(10) ), depois de gravar o caractere final no Output arquivo.WriteLine inserts a newline character (that is, a carriage return/line feed, or Chr(13) + Chr(10)), after it has written the final character in Output to the file.
Você pode inserir aspas em uma cadeia de caracteres usando aspas duplas ou "".You can embed quotation marks in a string by using double quotation marks, or "". Por exemplo,For example,
Dim x As String = "Double quotation marks aren't ""difficult"" to handle."
Retorna uma cadeia de caracteres com o valor de Double quotation marks aren't "difficult" to handle .returns a string with the value of Double quotation marks aren't "difficult" to handle.
Gravar em um arquivo usando as Write funções ou WriteLine requer Append acesso da FileIOPermissionAccess enumeração.Writing to a file by using the Write or WriteLine functions requires Append access from the FileIOPermissionAccess enumeration. Para obter mais informações, consulte FileIOPermissionAccess.For more information, see FileIOPermissionAccess .
Aplica-se a
Confira também
- WriteLine(Int32, Object[])
- Input
- FileOpen(Int32, String, OpenMode, OpenAccess, OpenShare, Int32)
- Print(Int32, Object[])
- PrintLine(Int32, Object[])
- Access de arquivo com o Visual BasicFile Access with Visual Basic
- Como gravar texto em arquivos no Visual BasicHow to: Write Text to Files in Visual Basic
- Como: gravar texto em um arquivo com um StreamWriter (Visual Basic)How to: Write Text to a File with a Streamwriter (Visual Basic)