C# File OpenText

Description

File OpenText Opens an existing UTF-8 encoded text file for reading.

Syntax

File.OpenText has the following syntax.


public static StreamReader OpenText(
  string path
)

Parameters

File.OpenText has the following parameters.

  • path - The file to be opened for reading.

Returns

File.OpenText method returns A StreamReader on the specified path.

Example

The following example creates a file for text writing and reading.


/*from  www . j  a  v a2  s. co  m*/
using System;
using System.IO;

class Test 
{
    public static void Main() 
    {
        string path = @"c:\temp\MyTest.txt";
        if (!File.Exists(path)) 
        {
            using (StreamWriter sw = File.CreateText(path)) 
            {
                sw.WriteLine("Hello");
                sw.WriteLine("And");
                sw.WriteLine("Welcome");
            }  
        }
        using (StreamReader sr = File.OpenText(path)) 
        {
            string s = "";
            while ((s = sr.ReadLine()) != null) 
            {
                Console.WriteLine(s);
            }
        }
    }
}




















Home »
  C# Tutorial »
    System.IO »




BinaryReader
BinaryWriter
Directory
DirectoryInfo
DriveInfo
File
FileInfo
FileStream
MemoryStream
Path
StreamReader
StreamWriter
StringReader
StringWriter