Guide pratique pour écrire du texte dans un fichier

Cet article présente différentes façons d’écrire du texte dans un fichier pour une application .NET.

Les classes et méthodes suivantes sont généralement utilisées pour écrire du texte dans un fichier :

  • StreamWriter contient des méthodes permettant d’écrire dans un fichier de façon synchrone (Write et WriteLine) ou asynchrone (WriteAsync et WriteLineAsync).

  • File fournit des méthodes statiques pour écrire du texte dans un fichier, comme WriteAllLines et WriteAllText, ou pour ajouter du texte à un fichier, comme AppendAllLines, AppendAllText et AppendText.

  • Path concerne les chaînes qui contiennent des informations relatives au chemin d’un fichier ou d’un répertoire. Il contient la méthode Combine et dans .NET Core 2.1 et versions ultérieures, les méthodes Join et TryJoin. Ces méthodes permettent de concaténer des chaînes pour générer un chemin d’accès au fichier ou au répertoire.

Notes

Les exemples suivants ne montrent que la quantité minimale de code nécessaire. Une application réelle fournit généralement une vérification des erreurs et une gestion des exceptions plus robuste.

Exemple : écrire du texte avec StreamWriter de façon synchrone

L’exemple suivant montre comment utiliser la classe StreamWriter pour écrire, ligne par ligne, du texte de façon synchrone dans un nouveau fichier. Étant donné que l’objet StreamWriter est déclaré et instancié dans une instruction using, la méthode Dispose est appelée, ce qui vide et ferme automatiquement le flux.

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

Exemple : ajouter du texte avec StreamWriter de façon synchrone

L’exemple suivant montre comment utiliser la classe StreamWriter pour ajouter du texte de façon synchrone au fichier texte créé dans le premier exemple :

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

Exemple : écrire du texte avec StreamWriter de façon asynchrone

L’exemple suivant montre comment écrire du texte de façon asynchrone dans un nouveau fichier à l’aide de la classe StreamWriter . Pour appeler la méthode WriteAsync, l’appel de méthode doit se trouver dans une méthode async.

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.

Exemple : écrire et ajouter du texte avec la classe File

L’exemple suivant montre comment écrire du texte dans un nouveau fichier et ajouter de nouvelles lignes de texte à ce même fichier à l’aide de la classe File . Les méthodes WriteAllText et AppendAllLines ouvrent et ferment automatiquement le fichier. Si le chemin que vous fournissez à la méthode WriteAllText existe déjà, le fichier est remplacé.

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

Voir aussi