Was this page helpful?
Your feedback about this content is important. Let us know what you think.
Additional feedback?
1500 characters remaining
Export (0) Print
Expand All

File.OpenText Method

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

Namespace:  System.IO
Assembly:  mscorlib (in mscorlib.dll)

'Declaration
Public Shared Function OpenText ( _
	path As String _
) As StreamReader

Parameters

path
Type: System.String

The file to be opened for reading.

Return Value

Type: System.IO.StreamReader
A StreamReader on the specified path.

ExceptionCondition
UnauthorizedAccessException

The caller does not have the required permission.

ArgumentException

path is a zero-length string, contains only white space, or contains one or more invalid characters as defined by InvalidPathChars.

ArgumentNullException

path is Nothing.

PathTooLongException

The specified path, file name, or both exceed the system-defined maximum length. For example, on Windows-based platforms, paths must be less than 248 characters, and file names must be less than 260 characters.

DirectoryNotFoundException

The specified path is invalid, (for example, it is on an unmapped drive).

FileNotFoundException

The file specified in path was not found.

NotSupportedException

path is in an invalid format.

This method is equivalent to the StreamReader(String) constructor overload.

The path parameter is permitted to specify relative or absolute path information. Relative path information is interpreted as relative to the current working directory. To obtain the current working directory, see GetCurrentDirectory.

For a list of common I/O tasks, see Common I/O Tasks.

The following example opens a text file for reading.

Imports System
Imports System.IO
Imports System.Text

Public Class Test
  Public Shared Sub Main()
    Dim path As String = "c:\temp\MyTest.txt" 

    If Not File.Exists(path) Then 
      ' Create the file. 
      Using fs As FileStream = File.Create(path)
        Dim info As Byte() = _
         New UTF8Encoding(True).GetBytes("This is some text in the file.")

        ' Add some information to the file.
        fs.Write(info, 0, info.Length)
      End Using 
    End If 

    ' Open the stream and read it back.  
    Using sr As StreamReader = File.OpenText(path)
      Do While sr.Peek() >= 0
        Console.WriteLine(sr.ReadLine())
      Loop 
    End Using 

  End Sub 
End Class

.NET Framework

Supported in: 4.6, 4.5, 4, 3.5, 3.0, 2.0, 1.1

.NET Framework Client Profile

Supported in: 4, 3.5 SP1

XNA Framework

Supported in: 3.0, 2.0, 1.0

Supported in: Windows Phone 8.1

Supported in: Windows Phone Silverlight 8.1

Supported in: Windows Phone Silverlight 8

Show:
© 2015 Microsoft