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


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

File.OpenRead(String)是一個內置的File類方法,用於打開現有文件進行讀取。

用法:

public static System.IO.FileStream OpenRead (string path);

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



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

異常:

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

返回值:返回指定路徑上的隻讀FileStream。

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

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

file.txt

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

// C# program to illustrate the usage 
// of File.OpenRead(String) method 
  
// Using System, System.IO and 
// System.Text namespaces 
using System; 
using System.IO; 
using System.Text; 
  
class Test { 
    public static void Main() 
    { 
        // Specifing a file 
        string path = @"file.txt"; 
  
        // Opening the existing file for reading 
        using(FileStream fs = File.OpenRead(path)) 
        { 
            byte[] b = new byte[1024]; 
            UTF8Encoding temp = new UTF8Encoding(true); 
  
            while (fs.Read(b, 0, b.Length) > 0) { 
                // Printing the file contents 
                Console.WriteLine(temp.GetString(b)); 
            } 
        } 
    } 
}

執行中:

GeeksforGeeks

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

file.txt

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

// C# program to illustrate the usage 
// of File.OpenRead(String) method 
  
// Using System, System.IO and 
// System.Text namespaces 
using System; 
using System.IO; 
using System.Text; 
  
class GFG { 
    public static void Main() 
    { 
        // Specifing a file 
        string path = @"file.txt"; 
  
        // Opening the file for overwriting with 
        // another contents 
        using(FileStream fs = File.OpenWrite(path)) 
        { 
            Byte[] info = new UTF8Encoding(true).GetBytes("GFG is a CS portal."); 
            fs.Write(info, 0, info.Length); 
        } 
  
        // Opening the existing file for reading 
        using(FileStream fs = File.OpenRead(path)) 
        { 
            byte[] b = new byte[1024]; 
            UTF8Encoding temp = new UTF8Encoding(true); 
  
            while (fs.Read(b, 0, b.Length) > 0) { 
                // Printing the file contents 
                Console.WriteLine(temp.GetString(b)); 
            } 
        } 
    } 
}

執行中:

GFG is a CS portal.



相關用法


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