sábado, 24 de julio de 2021

How to read from a text file (C# Programming Guide)

 https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/file-system/how-to-read-from-a-text-file

This example reads the contents of a text file by using the static methods ReadAllText and ReadAllLines from the System.IO.File class.

For an example that uses StreamReader, see How to read a text file one line at a time.

 Note

The files that are used in this example are created in the topic How to write to a text file.

Example

C#
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();
    }
}

Compiling the Code

Copy the code and paste it into a C# console application.

If you are not using the text files from How to write to a text file, replace the argument to ReadAllText and ReadAllLines with the appropriate path and file name on your computer.

Robust Programming

The following conditions may cause an exception:

  • The file doesn't exist or doesn't exist at the specified location. Check the path and the spelling of the file name.

.NET Security

Do not rely on the name of a file to determine the contents of the file. For example, the file myFile.cs might not be a C# source file.

See also

How to write to a text file (C# Programming Guide)

 https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/file-system/how-to-write-to-a-text-file

How to write to a text file (C# Programming Guide)

In this article, there are several examples showing various ways to write text to a file. The first two examples use static convenience methods on the System.IO.File class to write each element of any IEnumerable<string> and a string to a text file. The third example shows how to add text to a file when you have to process each line individually as you write to the file. In the first three examples, you overwrite all existing content in the file. The final example shows how to append text to an existing file.

These examples all write string literals to files. If you want to format text written to a file, use the Format method or C# string interpolation feature.

Write a collection of strings to a file

C#
using System.IO;
using System.Threading.Tasks;

class WriteAllLines
{
    public static async Task ExampleAsync()
    {
        string[] lines =
        {
            "First line", "Second line", "Third line" 
        };

        await File.WriteAllLinesAsync("WriteLines.txt", lines);
    }
}

The preceding source code example:

  • Instantiates a string array with three values.

  • Awaits a call to File.WriteAllLinesAsync which:

    • Asynchronously creates a file name WriteLines.txt. If the file already exists, it is overwritten.
    • Writes the given lines to the file.
    • Closes the file, automatically flushing and disposing as needed.

Write one string to a file

C#
using System.IO;
using System.Threading.Tasks;

class WriteAllText
{
    public static async Task ExampleAsync()
    {
        string text =
            "A class is the most powerful data type in C#. Like a structure, " +
            "a class defines the data and behavior of the data type. ";

        await File.WriteAllTextAsync("WriteText.txt", text);
    }
}

The preceding source code example:

  • Instantiates a string given the assigned string literal.

  • Awaits a call to File.WriteAllTextAsync which:

    • Asynchronously creates a file name WriteText.txt. If the file already exists, it is overwritten.
    • Writes the given text to the file.
    • Closes the file, automatically flushing and disposing as needed.

Write selected strings from an array to a file

C#
using System.IO;
using System.Threading.Tasks;

class StreamWriterOne
{
    public static async Task ExampleAsync()
    {
        string[] lines = { "First line", "Second line", "Third line" };
        using StreamWriter file = new("WriteLines2.txt");

        foreach (string line in lines)
        {
            if (!line.Contains("Second"))
            {
                await file.WriteLineAsync(line);
            }
        }
    }
}

The preceding source code example:

Append text to an existing file

C#
using System.IO;
using System.Threading.Tasks;

class StreamWriterTwo
{
    public static async Task ExampleAsync()
    {
        using StreamWriter file = new("WriteLines2.txt", append: true);
        await file.WriteLineAsync("Fourth line");
    }
}

The preceding source code example:

Exceptions

The following conditions may cause an exception:

There are additional conditions that may cause exceptions when working with the file system, it is best to program defensively.

See also

sábado, 3 de julio de 2021