Scrittura di testo in un file

Nell'esempio di codice che segue viene illustrato un modo semplice per scrivere testo in un file di testo.

Imports System
Imports System.IO

Class Test
    Public Shared Sub Main()
        ' Create an instance of StreamWriter to write text to a file.
        Dim sw As StreamWriter = New StreamWriter("TestFile.txt")
        ' Add some text to the file.
        sw.Write("This is the ")
        sw.WriteLine("header for the file.")
        sw.WriteLine("-------------------")
        ' Arbitrary objects can also be written to the file.
        sw.Write("The date is: ")
        sw.WriteLine(DateTime.Now)
        sw.Close()
    End Sub
End Class

[C#]
using System;
using System.IO;

class Test 
{
    public static void Main() 
    {
        // Create an instance of StreamWriter to write text to a file.
        // The using statement also closes the StreamWriter.
        using (StreamWriter sw = new StreamWriter("TestFile.txt")) 
        {
            // Add some text to the file.
            sw.Write("This is the ");
            sw.WriteLine("header for the file.");
            sw.WriteLine("-------------------");
            // Arbitrary objects can also be written to the file.
            sw.Write("The date is: ");
            sw.WriteLine(DateTime.Now);
        }
    }
}

Nell'esempio di codice che segue viene creato un nuovo file di testo e viene scritta una stringa all'interno del file.

Option Explicit On 
Option Strict On
Imports System
Imports System.IO
Public Class TextToFile
    Private Const FILE_NAME As String = "MyFile.txt"
    Public Shared Sub Main()
        If File.Exists(FILE_NAME) Then
            Console.WriteLine("{0} already exists.", FILE_NAME)
            Return
        End If
        Dim sr As StreamWriter = File.CreateText(FILE_NAME)
        sr.WriteLine("This is my file.")
        sr.WriteLine("I can write ints {0} or floats {1}, and so on.", 1, 4.2)
        sr.Close()
    End Sub
End Class

[C#]
using System;
using System.IO;
public class TextToFile 
{
    private const string FILE_NAME = "MyFile.txt";
    public static void Main(String[] args) 
    {
        if (File.Exists(FILE_NAME)) 
        {
            Console.WriteLine("{0} already exists.", FILE_NAME);
            return;
        }
        StreamWriter sr = File.CreateText(FILE_NAME);
        sr.WriteLine ("This is my file.");
        sr.WriteLine ("I can write ints {0} or floats {1}, and so on.", 
            1, 4.2);
        sr.Close();
    }
}

Vedere anche

Creazione di un elenco di directory | Lettura e scrittura in un nuovo file di dati | Apertura e aggiunta a un file di log | Lettura di testo da un file | Lettura di caratteri da una stringa | Scrittura di caratteri in una stringa | I/O di file di base | StreamWriter | File.CreateText