didactics (10)

  • docx
  • 02.05.2020
Публикация на сайте для учителей

Публикация педагогических разработок

Бесплатное участие. Свидетельство автора сразу.
Мгновенные 10 документов в портфолио.

Иконка файла материала didactics (10).docx

How to: Read From a Text File

 

class ReadFromFile

{

    static void Main()

    {

                // 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();

    }

}

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.

 

How to: Read a Text File One Line at a Time

This example reads the contents of a text file, one line at a time, into a string using the ReadLine method of the StreamReader class. Each text line is stored into the string line and displayed on the screen.

 

Example

 

int counter = 0; 

string line; 

 

// Read the file and display it line by line. 

System.IO.StreamReader file =  

    new System.IO.StreamReader(@"c:\test.txt"); 

while((line = file.ReadLine()) != null) 

    System.Console.WriteLine(line); 

    counter++; 

 

file.Close(); 

System.Console.WriteLine("There were {0} lines.", counter); 

// Suspend the screen. 

System.Console.ReadLine(); 

 

Compiling the Code

Copy the code and paste it into the Main method of a console application.

Replace "c:\test.txt" with the actual file name.

 

The following conditions may cause an exception:

The file may not exist.

 

 

 

Write to a Text File

 

These examples show 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. Example 3 shows how to add text to a file when you have to process each line individually as you write to the file. Examples 1-3 overwrite all existing content in the file, but example 4 shows you how to append text to an existing file.

class WriteTextFile

{

    static void Main()

    {

 

        // These examples assume a "C:\Users\Public\TestFolder" folder on your machine.

        // You can modify the path if necessary.

       

 

        // Example #1: Write an array of strings to a file.

        // Create a string array that consists of three lines.

        string[] lines = { "First line", "Second line", "Third line" };

        // WriteAllLines creates a file, writes a collection of strings to the file,

        // and then closes the file.  You do NOT need to call Flush() or Close().

        System.IO.File.WriteAllLines(@"C:\Users\Public\TestFolder\WriteLines.txt", lines);

 

 

        // Example #2: Write one string to a text file.

        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. ";

        // WriteAllText creates a file, writes the specified string to the file,

        // and then closes the file.    You do NOT need to call Flush() or Close().

        System.IO.File.WriteAllText(@"C:\Users\Public\TestFolder\WriteText.txt", text);

 

        // Example #3: Write only some strings in an array to a file.

        // The using statement automatically flushes AND CLOSES the stream and calls

        // IDisposable.Dispose on the stream object.

        // NOTE: do not use FileStream for text files because it writes bytes, but StreamWriter

        // encodes the output as text.

        using (System.IO.StreamWriter file =

            new System.IO.StreamWriter(@"C:\Users\Public\TestFolder\WriteLines2.txt"))

        {

            foreach (string line in lines)

            {

                // If the line doesn't contain the word 'Second', write the line to the file.

                if (!line.Contains("Second"))

                {

                    file.WriteLine(line);

                }

            }

        }

 

        // Example #4: Append new text to an existing file.

        // The using statement automatically flushes AND CLOSES the stream and calls

        // IDisposable.Dispose on the stream object.

        using (System.IO.StreamWriter file =

            new System.IO.StreamWriter(@"C:\Users\Public\TestFolder\WriteLines2.txt", true))

        {

            file.WriteLine("Fourth line");

        }

    }

}

 //Output (to WriteLines.txt):

 //   First line

 //   Second line

 //   Third line

    

 //Output (to WriteText.txt):

 //   A class is the most powerful data type in C#. Like a structure, a class defines the data and behavior of the data type.

    

 //Output to WriteLines2.txt after Example #3:

 //   First line

 //   Third line

     

 //Output to WriteLines2.txt after Example #4:

 //   First line

 //   Third line

 //   Fourth line

 

The following conditions may cause an exception:

The file exists and is read-only.

The path name may be too long.

The disk may be full.

 

 

 

Links:

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

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

 

 

 


 

Скачано с www.znanio.ru