File.OpenText(String) 方法
定義
重要
部分資訊涉及發行前產品,在發行之前可能會有大幅修改。 Microsoft 對此處提供的資訊,不做任何明確或隱含的瑕疵擔保。
開啟一個現有的 UTF-8 編碼文字檔以供閱讀。
public:
static System::IO::StreamReader ^ OpenText(System::String ^ path);
public static System.IO.StreamReader OpenText(string path);
static member OpenText : string -> System.IO.StreamReader
Public Shared Function OpenText (path As String) As StreamReader
參數
- path
- String
檔案要打開閱讀。
傳回
StreamReader A 在指定的路徑上。
例外狀況
來電者沒有所需的權限。
.NET Framework 與 .NET Core 版本 2.1 以前: path 為零長度字串、僅含空白,或包含一個或多個無效字元。 你可以用這個 GetInvalidPathChars() 方法查詢無效字元。
path 是 null。
指定的路徑、檔名或兩者都超過系統定義的最大長度。
指定的路徑無效(例如,它位於未映射的硬碟上)。
未找到該檔案 path 。
path 格式無效。
範例
以下範例會開啟一個文字檔以便閱讀。
using System;
using System.IO;
using System.Text;
class Test
{
public static void Main()
{
string path = @"c:\temp\MyTest.txt";
if (!File.Exists(path))
{
// Create the file.
using (FileStream fs = File.Create(path))
{
Byte[] info =
new UTF8Encoding(true).GetBytes("This is some text in the file.");
// Add some information to the file.
fs.Write(info, 0, info.Length);
}
}
// Open the stream and read it back.
using (StreamReader sr = File.OpenText(path))
{
string s = "";
while ((s = sr.ReadLine()) != null)
{
Console.WriteLine(s);
}
}
}
}
open System.IO
open System.Text
let path = @"c:\temp\MyTest.txt"
if File.Exists path |> not then
// Create the file.
use fs = File.Create path
let info =
UTF8Encoding(true)
.GetBytes "This is some text in the file."
// Add some information to the file.
fs.Write(info, 0, info.Length)
// Open the stream and read it back.
do
use sr = File.OpenText path
let mutable s = sr.ReadLine()
while isNull s |> not do
printfn $"{s}"
s <- sr.ReadLine()
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
備註
此方法等同 StreamReader(String) 於建構子過載。
path參數允許指定相對或絕對路徑資訊。 相對路徑資訊會被解讀為相對於目前工作目錄的相對於。 欲取得目前的工作目錄,請參見 GetCurrentDirectory。
關於常見 I/O 任務的清單,請參見 Common I/O 任務。