Procedura: Scrivere testo in un fileHow to: Write text to a file
Questo argomento illustra diversi modi per scrivere testo in un file per un'app .NET.This topic shows different ways to write text to a file for a .NET app.
Per scrivere un testo in un file vengono in genere usati le classi e i metodi seguenti:The following classes and methods are typically used to write text to a file:
StreamWriter contiene metodi per scrivere in un file in modo sincrono (Write e WriteLine) o asincrono (WriteAsync e WriteLineAsync).StreamWriter contains methods to write to a file synchronously (Write and WriteLine) or asynchronously (WriteAsync and WriteLineAsync).
File specifica metodi statici per scrivere un testo in un file, ad esempio WriteAllLines e WriteAllText o per accodare testo a un file, ad esempio AppendAllLines, AppendAllText e AppendText.File provides static methods to write text to a file, such as WriteAllLines and WriteAllText, or to append text to a file, such as AppendAllLines, AppendAllText, and AppendText.
Path è destinato alle stringhe che contengono informazioni sul percorso di file o directory.Path is for strings that have file or directory path information. Contiene il metodo Combine e in .NET Core 2.1 e versioni successive i metodi Join e TryJoin, che consentono la concatenazione di stringhe per compilare un percorso di file o directory.It contains the Combine method and, in .NET Core 2.1 and later, the Join and TryJoin methods, which allow concatenation of strings to build a file or directory path.
Nota
Gli esempi seguenti visualizzano solo la quantità minima di codice necessario.The following examples show only the minimum amount of code needed. Un'applicazione reale include in genere procedure di controllo degli errori e di gestione delle eccezioni più efficaci.A real-world app usually provides more robust error checking and exception handling.
Esempio: Scrivere testo in modo sincrono con StreamWriterExample: Synchronously write text with StreamWriter
L'esempio seguente illustra come usare la classe StreamWriter per scrivere un testo in modo sincrono una riga alla volta in un nuovo file.The following example shows how to use the StreamWriter class to synchronously write text to a new file one line at a time. Poiché l'oggetto StreamWriter viene dichiarato in un'istruzione using
in cui viene creata anche un'istanza dell'oggetto stesso, viene chiamato il metodo Dispose che scarica e chiude automaticamente il flusso.Because the StreamWriter object is declared and instantiated in a using
statement, the Dispose method is invoked, which automatically flushes and closes the stream.
using System;
using System.IO;
class Program
{
static void Main(string[] args)
{
// Create a string array with the lines of text
string[] lines = { "First line", "Second line", "Third line" };
// Set a variable to the Documents path.
string docPath =
Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
// Write the string array to a new file named "WriteLines.txt".
using (StreamWriter outputFile = new StreamWriter(Path.Combine(docPath, "WriteLines.txt")))
{
foreach (string line in lines)
outputFile.WriteLine(line);
}
}
}
// The example creates a file named "WriteLines.txt" with the following contents:
// First line
// Second line
// Third line
Imports System.IO
Class WriteText
Public Shared Sub Main()
' Create a string array with the lines of text
Dim lines() As String = {"First line", "Second line", "Third line"}
' Set a variable to the Documents path.
Dim docPath As String = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
' Write the string array to a new file named "WriteLines.txt".
Using outputFile As New StreamWriter(Path.Combine(docPath, Convert.ToString("WriteLines.txt")))
For Each line As String In lines
outputFile.WriteLine(line)
Next
End Using
End Sub
End Class
' The example creates a file named "WriteLines.txt" with the following contents:
' First line
' Second line
' Third line
Esempio: Accodare testo in modo sincrono con StreamWriterExample: Synchronously append text with StreamWriter
L'esempio seguente illustra come usare la classe StreamWriter per accodare testo in modo sincrono al file di testo creato nel primo esempio.The following example shows how to use the StreamWriter class to synchronously append text to the text file created in the first example.
using System;
using System.IO;
class Program
{
static void Main(string[] args)
{
// Set a variable to the Documents path.
string docPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
// Append text to an existing file named "WriteLines.txt".
using (StreamWriter outputFile = new StreamWriter(Path.Combine(docPath, "WriteLines.txt"), true))
{
outputFile.WriteLine("Fourth Line");
}
}
}
// The example adds the following line to the contents of "WriteLines.txt":
// Fourth Line
Imports System.IO
Class AppendText
Public Shared Sub Main()
' Set a variable to the Documents path.
Dim docPath As String =
Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
' Append text to an existing file named "WriteLines.txt".
Using outputFile As New StreamWriter(Path.Combine(docPath, Convert.ToString("WriteLines.txt")), True)
outputFile.WriteLine("Fourth Line")
End Using
End Sub
End Class
' The example adds the following line to the contents of "WriteLines.txt":
' Fourth Line
Esempio: Scrivere testo in modo asincrono con StreamWriterExample: Asynchronously write text with StreamWriter
L'esempio seguente illustra come scrivere in modo asincrono un testo in un nuovo file usando la classe StreamWriter .The following example shows how to asynchronously write text to a new file using the StreamWriter class. Per chiamare il metodo WriteAsync, la chiamata al metodo deve essere inclusa in un metodo async
.To invoke the WriteAsync method, the method call must be within an async
method. L'esempio C# richiede C# 7.1 o versioni successive, che aggiunge il supporto per il modificatore async
nel punto di ingresso del programma.The C# example requires C# 7.1 or later, which adds support for the async
modifier on the program entry point.
using System;
using System.IO;
using System.Threading.Tasks;
class Program
{
static async Task Main()
{
// Set a variable to the Documents path.
string docPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
// Write the specified text asynchronously to a new file named "WriteTextAsync.txt".
using (StreamWriter outputFile = new StreamWriter(Path.Combine(docPath, "WriteTextAsync.txt")))
{
await outputFile.WriteAsync("This is a sentence.");
}
}
}
// The example creates a file named "WriteTextAsync.txt" with the following contents:
// This is a sentence.
Imports System.IO
Public Module Example
Public Sub Main()
WriteTextAsync()
End Sub
Async Sub WriteTextAsync()
' Set a variable to the Documents path.
Dim docPath As String = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
' Write the text asynchronously to a new file named "WriteTextAsync.txt".
Using outputFile As New StreamWriter(Path.Combine(docPath, Convert.ToString("WriteTextAsync.txt")))
Await outputFile.WriteAsync("This is a sentence.")
End Using
End Sub
End Module
' The example creates a file named "WriteTextAsync.txt" with the following contents:
' This is a sentence.
Esempio: Scrivere e accodare testo con la classe FileExample: Write and append text with the File class
L'esempio seguente illustra come scrivere un testo in un nuovo file e aggiungere nuove righe di testo nello stesso file usando la classe File .The following example shows how to write text to a new file and append new lines of text to the same file using the File class. I metodi WriteAllText e AppendAllLines aprono e chiudono automaticamente il file.The WriteAllText and AppendAllLines methods open and close the file automatically. Se il percorso specificato per il metodo WriteAllText esiste già, il file viene sovrascritto.If the path you provide to the WriteAllText method already exists, the file is overwritten.
using System;
using System.IO;
class Program
{
static void Main(string[] args)
{
// Create a string with a line of text.
string text = "First line" + Environment.NewLine;
// Set a variable to the Documents path.
string docPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
// Write the text to a new file named "WriteFile.txt".
File.WriteAllText(Path.Combine(docPath, "WriteFile.txt"), text);
// Create a string array with the additional lines of text
string[] lines = { "New line 1", "New line 2" };
// Append new lines of text to the file
File.AppendAllLines(Path.Combine(docPath, "WriteFile.txt"), lines);
}
}
// The example creates a file named "WriteFile.txt" with the contents:
// First line
// And then appends the following contents:
// New line 1
// New line 2
Imports System.IO
Class WriteFile
Public Shared Sub Main()
' Create a string array with the lines of text
Dim text As String = "First line" & Environment.NewLine
' Set a variable to the Documents path.
Dim docPath As String = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
' Write the text to a new file named "WriteFile.txt".
File.WriteAllText(Path.Combine(docPath, Convert.ToString("WriteFile.txt")), text)
' Create a string array with the additional lines of text
Dim lines() As String = {"New line 1", "New line 2"}
' Append new lines of text to the file
File.AppendAllLines(Path.Combine(docPath, Convert.ToString("WriteFile.txt")), lines)
End Sub
End Class
' The example creates a file named "WriteFile.txt" with the following contents:
' First line
' And then appends the following contents:
' New line 1
' New line 2
Vedere ancheSee also
- StreamWriter
- Path
- File.CreateText
- Procedura: Enumerare directory e fileHow to: Enumerate directories and files
- Procedura: Leggere e scrivere su un file di dati appena creatoHow to: Read and write to a newly-created data file
- Procedura: Aprire e accodare un file di logHow to: Open and append to a log file
- Procedura: Leggere testo da un fileHow to: Read text from a file
- I/O di file e di flussiFile and stream I/O
Commenti
Caricamento dei commenti...