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


C# File.Open(String, FileMode)用法及代碼示例

File.Open(String, FileMode)是一個內置的 File 類方法,用於打開指定路徑上的 FileStream,具有讀/寫訪問權限,沒有共享。
用法:

public static System.IO.FileStream Open (string path, System.IO.FileMode mode);

參數:此函數接受兩個參數,如下所示:

  • sourceFileName: This is the specified file to open.
  • mode: This mode value specifies whether a new file is created if one does not exist, and also determines whether the existing file’s contents are retained or overwritten.

異常:

  • ArgumentException:路徑是一個長度為零的字符串,隻包含空格,或者一個或多個由 InvalidPathChars 定義的無效字符。
  • ArgumentNullException:路徑為空。
  • PathTooLongException:給定的路徑、文件名或兩者都超過了 system-defined 的最大長度。
  • DirectoryNotFoundException:指定的路徑無效。
  • IOException:打開文件時發生I /O錯誤。
  • UnauthorizedAccessException:路徑指定了一個隻讀文件。 OR 當前平台不支持此操作。或者路徑指定了一個目錄。或調用者沒有所需的權限。或模式為已創建且指定的文件為隱藏文件。
  • ArgumentOutOfRangeException:模式指定了無效值。
  • FileNotFoundException:找不到路徑中指定的文件。
  • NotSupportedException:路徑格式無效。

返回值:返回以指定模式和路徑打開的 FileStream,具有讀/寫訪問權限且不共享。
下麵是說明 File.Open(String, FileMode) 方法的程序。
程序1:下麵的代碼創建一個臨時文件,將一些指定的內容寫入其中,然後打開文件並打印它。

C#


// C# program to illustrate the usage
// of File.Open(String, FileMode) method
// Using System, System.IO and
// System.Text namespaces
using System;
using System.IO;
using System.Text;
class GFG {
    public static void Main()
    {
        // Creating a temporary file
        string path = Path.GetTempFileName();
        using(FileStream fs = File.Open(path, FileMode.Open))
        {
            // Putting some contents
            Byte[] info = new UTF8Encoding(true).GetBytes("GFG is a CS Portal.");
            fs.Write(info, 0, info.Length);
        }
        // Opening the stream and reading it back.
        using(FileStream fs = File.Open(path, FileMode.Open))
        {
            byte[] b = new byte[1024];
            UTF8Encoding temp = new UTF8Encoding(true);
            while (fs.Read(b, 0, b.Length) > 0) {
                Console.WriteLine(temp.GetString(b));
            }
        }
    }
}

輸出:

GFG is a CS Portal.

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

file.txt

下麵的代碼將打開文件 file.txt 並打印其內容。

C#


// C# program to illustrate the usage
// of File.Open(String, FileMode) method
// Using System, System.IO and
// System.Text namespaces
using System;
using System.IO;
using System.Text;
class GFG {
    public static void Main()
    {
        // Specifying a file path
        string path = @"file.txt";
        // Opening above file and reading it back.
        using(FileStream fs = File.Open(path, FileMode.Open))
        {
            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

相關用法


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