How to read and write data to a text file by using Visual C #

Source: Internet
Author: User
Tags finally block
Read and Write text files

Loadtocnode (2, 'summary ');

Read a text file

This section describes how to useStreamreader
Class to read text files. Write a text file (Example 1)

And write a text file (Example 2)

Each section describes how to useStreamwriter
Class to write text to a file.

Read text files

Loadtocnode (3, 'summary ');

Use the following codeStreamreader
Class to open, read, and close the text file. You can pass the path of a text file to automatically open the file.
Streamreader
Constructor.Readline
Method to read each line of text, and then increment the file pointer to the next line according to its reading.
Readline
When the method reaches the end of the file, it returns an empty reference.

  1. Create an example text file in notepad. To perform this operation, follow these steps:

    1. Paste the following text in Notepad:

      hello world
    2. Save the file as sample.txt.
  2. Start Microsoft Visual Studio.
  3. InFile
    PointNew
    And then clickProject
    .
  4. InProject Type
    , ClickVisual C #
    Project

    And then clickTemplate
    UnderConsole Application

    Note:
    In Visual Studio 2005 or visual
    Maxcompute studio 2008, clickVisual C #
    Project Type
    , And then clickTemplate
    UnderConsole Application
    .

  5. Add the following code at the beginning of the class1.cs file:
    using System.IO;

    Note:
    In the visual
    Studio 2005 or Visual Studio 2008. The default file is program. CS.

  6. Add the following codeMain
    Method:

    String line;
    try
    {
    //Pass the file path and file name to the StreamReader constructor
    StreamReader sr = new StreamReader("C:\\Sample.txt");

    //Read the first line of text
    line = sr.ReadLine();

    //Continue to read until you reach end of file
    while (line != null)
    {
    //write the lie to console window
    Console.WriteLine(line);
    //Read the next line
    line = sr.ReadLine();
    }

    //close the file
    sr.Close();
    Console.ReadLine();
    }
    catch(Exception e)
    {
    Console.WriteLine("Exception: " + e.Message);
    }
    finally
    {
    Console.WriteLine("Executing finally block.");
    }

    Block.

  7. InDebugging
    ClickStart
    Compile and run the application. Press enter to close the console window. The console window is displayed in the sample.txt file.

    Hello world

    Content in

Write a text file (Example 1)

Loadtocnode (3, 'summary ');

Use the following codeStreamwriter
Class, and close the text file.Streamreader

Class in a similar way, you can pass the path of the text file to automatically open the fileStreamwriter
Constructor.Writeline

Method To write a complete text line to a text file.

  1. Start Visual Studio.
  2. InFile
    PointNew
    And then clickProject
    .
  3. InProject Type
    , ClickVisual C #
    Project

    And then clickTemplate
    UnderConsole Application
    .

    Note:
    In Visual Studio 2005 or visual
    Maxcompute studio 2008, clickVisual C #
    Project Type
    , And then clickTemplate
    UnderCLR console application
    .

  4. Add the following code at the beginning of the class1.cs file:
    using System.IO;
  5. Add the following codeMain
    Method:

    try 
    {

    //Pass the filepath and filename to the StreamWriter Constructor
    StreamWriter sw = new StreamWriter("C:\\Test.txt");

    //Write a line of text
    sw.WriteLine("Hello World!!");

    //Write a second line of text
    sw.WriteLine("From the StreamWriter class");

    //Close the file
    sw.Close();
    }
    catch(Exception e)
    {
    Console.WriteLine("Exception: " + e.Message);
    }
    finally
    {
    Console.WriteLine("Executing finally block.");
    }

    Block.

  6. InDebugging
    ClickStart

    Compile and run the application. This Code creates a file named test.txt too many characters before using C. open the file test.txt in a text editor (such as NotePad. Test.txt
    Contains two lines of text:

    Hello World!!
    From the StreamWriter class
Write a text file (Example 2)

Loadtocnode (3, 'summary ');

Use the following codeStreamwriter
Class, and close the text file. Unlike the previous example, this code passes two additional parameters to the constructor.
The first parameter is the file path and file name. Second ParameterTrue
To open the append mode of the file. If you specify
False
, The content of the file will overwrite the code every time it is run. The third parameter is specified.Unicode
ToStreamwriter

Unicode files are encoded. You can also specify the following encoding method for the third parameter:

  • Asc11
  • Unicode
  • Utf7
  • Utf8

Write
Method andWriteline
The method is similar
Write
The method does not automatically embed a carriage return or line feed (CR/LF) character combination. This is useful when you want to write one character at a time.

  1. Start Visual Studio.
  2. InFile
    PointNew
    And then clickProject
    .
  3. InProject Type
    , ClickVisual C #
    Project

    And then clickTemplate
    UnderConsole Application

    Note:
    In Visual Studio 2005 or visual
    Maxcompute studio 2008, clickVisual C #
    Project Type
    , And then clickTemplate
    UnderConsole Application

  4. Class1.cs
    Add the following code at the beginning of the file:

    using System.IO;
    using System.Text;

    Note:
    On Visual Studio 2005 or
    Visual Studio 2008. The default file is program. CS.

  5. Add the following codeMain
    Method:

    Int64 x;

    try
    {
    //Open the File
    StreamWriter sw = new StreamWriter("C:\\Test1.txt", true, Encoding.ASCII);

    //Writeout the numbers 1 to 10 on the same line.
    for(x=0; x < 10; x++)
    {
    sw.Write(x);
    }

    //close the file
    sw.Close();
    }
    catch(Exception e)
    {
    Console.WriteLine("Exception: " + e.Message);
    }
    finally
    {
    Console.WriteLine("Executing finally block.");
    }
  6. InDebugging
    ClickStart

    Compile and run the application. This Code creates a file named test1.txt. open the file test1.txt in a text editor (such as NotePad.
    Test1.txt contains a single line of text:

    0123456789
Please refer to the following link for more information 〃

Loadtocnode (3, 'summary ');

  • Read text files

    //Read a Text File
    using System;
    using System.IO;

    namespace readwriteapp
    {
    class Class1
    {
    [STAThread]
    static void Main(string[] args)
    {

    String line;

    try
    {
    //Pass the file path and file name to the StreamReader constructor
    StreamReader sr = new StreamReader("C:\\Sample.txt");

    //Read the first line of text
    line = sr.ReadLine();

    //Continue to read until you reach end of file
    while (line != null)
    {
    //write the lie to console window
    Console.WriteLine(line);
    //Read the next line
    line = sr.ReadLine();
    }

    //close the file
    sr.Close();
    Console.ReadLine();
    }
    catch(Exception e)
    {
    Console.WriteLine("Exception: " + e.Message);
    }
    finally
    {
    Console.WriteLine("Executing finally block.");
    }
    }
    }
    }

    Block.

  • Write a text file (version 1)
    //Write a text file - Version-1
    using System;
    using System.IO;

    namespace readwriteapp
    {
    class Class1
    {
    [STAThread]
    static void Main(string[] args)
    {
    try
    {

    //Pass the filepath and filename to the StreamWriter Constructor
    StreamWriter sw = new StreamWriter("C:\\Test.txt");

    //Write a line of text
    sw.WriteLine("Hello World!!");

    //Write a second line of text
    sw.WriteLine("From the StreamWriter class");

    //Close the file
    sw.Close();
    }
    catch(Exception e)
    {
    Console.WriteLine("Exception: " + e.Message);
    }
    finally
    {
    Console.WriteLine("Executing finally block.");
    }
    }
    }
    }

    Block.

  • Write a text file (version 2)
    //Write a text file  - Version 2
    using System;
    using System.IO;
    using System.Text;

    namespace readwriteapp
    {
    class Class1
    {
    [STAThread]
    static void Main(string[] args)
    {

    Int64 x;

    try
    {
    //Open the File
    StreamWriter sw = new StreamWriter("C:\\Test1.txt", true, Encoding.ASCII);

    //Writeout the numbers 1 to 10 on the same line.
    for(x=0; x < 10; x++)
    {
    sw.Write(x);
    }

    //close the file
    sw.Close();
    }
    catch(Exception e)
    {
    Console.WriteLine("Exception: " + e.Message);
    }
    finally
    {
    Console.WriteLine("Executing finally block.");
    }
    }
    }
    }
Troubleshooting

Loadtocnode (3, 'summary ');

It is a good programming habit for all file operations.Try-catch-finally
Block to handle errors and abnormal code.
Specifically, you may want to release the handle of the file in the last block so that the file is not locked indefinitely. Some possible errors include a file that does not exist or is in use.

For more information, visit the following Microsoft Developer Network (msdn) Website:

Streamreader class
Http://msdn2.microsoft.com/en-us/library/system.io.streamreader (vs.71). aspx


(Http://msdn2.microsoft.com/en-us/library/system.io.streamreader (vs.71). aspixel)

]

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.