Procedura: leggere da un file di testo (Guida per programmatori C#)

In questo esempio viene letto il contenuto di un file di testo tramite i metodi statici ReadAllText e ReadAllLines dalla classe System.IO.File.

Per un esempio in cui viene utilizzato un oggetto StreamReader, vedere Procedura: leggere un file di testo una riga alla volta (Visual C#).

[!NOTA]

I file utilizzati in questo esempio vengono creati nell'argomento Procedura: scrivere in un file di testo (Guida per programmatori C#).

Esempio

class ReadFromFile
{
    static void Main()
    {
        // The files used in this example are created in the topic
        // How to: Write to a Text File. You can change the path and
        // file name to substitute text files of your own.

        // Example #1
        // Read the file as one string.
        string text = System.IO.File.ReadAllText(@"C:\Users\Public\TestFolder\WriteText.txt");

        // Display the file contents to the console. Variable text is a string.
        System.Console.WriteLine("Contents of WriteText.txt = {0}", text);

        // Example #2
        // Read each line of the file into a string array. Each element
        // of the array is one line of the file.
        string[] lines = System.IO.File.ReadAllLines(@"C:\Users\Public\TestFolder\WriteLines2.txt");

        // Display the file contents by using a foreach loop.
        System.Console.WriteLine("Contents of WriteLines2.txt = ");
        foreach (string line in lines)
        {
            // Use a tab to indent each line of the file.
            Console.WriteLine("\t" + line);
        }

        // Keep the console window open in debug mode.
        Console.WriteLine("Press any key to exit.");
        System.Console.ReadKey();
    }
}

Compilazione del codice

Copiare il codice e incollarlo in un'applicazione console C#.

Se non si utilizzano i file di testo da Procedura: scrivere in un file di testo (Guida per programmatori C#), sostituire l'argomento in ReadAllText e a ReadAllLines con il percorso appropriato e il nome file nel computer.

Programmazione efficiente

Le seguenti condizioni possono generare un'eccezione:

  • Il file non esiste o non esiste nella posizione specificata.Verificare che il percorso e l'ortografia del nome file.

Sicurezza

Non basarsi sul nome di un file per determinare il contenuto del file.Ad esempio, il file myFile.cs non può essere un file di origine C#.

Vedere anche

Riferimenti

System.IO

Concetti

Guida per programmatori C#

Altre risorse

File system e Registro di sistema (Guida per programmatori C#)