當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


C# File.OpenText()用法及代碼示例

File.OpenText(String)是內置的File類方法,用於打開現有的UTF-8編碼文本文件進行讀取。

用法:

public static System.IO.StreamReader OpenText (string path);

參數:該函數接受如下所示的參數:



  • path: This is the specified text file which is going to be opened for reading.

異常:

  • UnauthorizedAccessException:調用者沒有所需的權限。
  • ArgumentException:路徑為長度為零的字符串,僅包含空格,或者由InvalidPathChars定義的一個或多個無效字符。
  • ArgumentNullException:路徑為空。
  • PathTooLongException:指定的路徑,文件名或兩者都超過了system-defined的最大長度。
  • DirectoryNotFoundException:指定的路徑無效。
  • FileNotFoundException:找不到在路徑中指定的文件。
  • NotSupportedException:路徑格式無效。

返回值:返回指定路徑上的StreamReader。

下麵是說明File.OpenText(String)方法的程序。

程序1:在運行以下代碼之前,將創建一個文本文件file.txt,其內容如下所示:

file.txt

在下麵的代碼中打開文本文件file.txt以進行讀取。

// C# program to illustrate the usage 
// of File.OpenText(String) method 
  
// Using System and System.IO 
// namespaces 
using System; 
using System.IO; 
  
class Test { 
    public static void Main() 
    { 
        // Specifing a text file 
        string path = @"file.txt"; 
  
        // Opening the file for reading 
        using(StreamReader sr = File.OpenText(path)) 
        { 
            string s = ""; 
            while ((s = sr.ReadLine()) != null) { 
                // printing the file contents 
                Console.WriteLine(s); 
            } 
        } 
    } 
}

執行中:

GeeksforGeeks

程序2:最初,將創建一個文件file.txt,其內容如下所示-

file.txt

下麵的代碼將用其他指定的內容覆蓋文件內容,然後將打印最終內容。

// C# program to illustrate the usage 
// of File.OpenText(String) method 
  
// Using System and System.IO 
// namespaces 
using System; 
using System.IO; 
  
class Test { 
    public static void Main() 
    { 
        // Specifing a text file 
        string path = @"file.txt"; 
  
        // Checking the existance of file 
        if (File.Exists(path)) { 
            using(StreamWriter sw = File.CreateText(path)) 
            { 
                // Overwriting the file with below 
                // specified contents 
                sw.WriteLine("GFG is a CS portal."); 
            } 
        } 
  
        // Opening the file for reading 
        using(StreamReader sr = File.OpenText(path)) 
        { 
            string s = ""; 
            while ((s = sr.ReadLine()) != null) { 
                // printing the overwritten content 
                Console.WriteLine(s); 
            } 
        } 
    } 
}

執行中:

GFG is a CS portal.



相關用法


注:本文由純淨天空篩選整理自Kanchan_Ray大神的英文原創作品 File.OpenText() Method in C# with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。