C#中的檔案操作是什麼?


C#具有以下檔案操作:

  • 建立、開啟、讀取和寫入檔案。
  • 追加,
  • 刪除等。

System.IO名稱空間中的FileStream類有助於讀取、寫入和關閉檔案。此類派生自抽象類Stream。

您需要建立一個FileStream物件來建立一個新檔案或開啟一個現有檔案。建立FileStream物件的語法如下:

FileStream = new FileStream( <file_name>, <FileMode Enumerator>,
<FileAccess Enumerator>, <FileShare Enumerator>);

此處,檔案操作也包含如下所示:

**FileMode**列舉定義了開啟檔案的各種方法。FileMode列舉的成員是:

  • **Append** - 開啟現有檔案並將游標置於檔案末尾,或者如果檔案不存在則建立檔案。

  • **Create** - 建立一個新檔案。

  • **CreateNew** - 向作業系統指定應建立一個新檔案。

  • **Open** - 開啟現有檔案。

  • **OpenOrCreate** - 向作業系統指定如果檔案存在則開啟檔案,否則建立新檔案。

  • **Truncate** - 開啟現有檔案並將大小截斷為零位元組。

**FileAccess** - FileAccess列舉具有以下成員:

  • 讀取,
  • 讀寫和
  • 寫入。

**FileShare** - FileShare列舉具有以下成員:

  • **Inheritable** - 允許檔案控制代碼將繼承傳遞給子程序

  • **None** - 拒絕共享當前檔案

  • **Read** - 允許開啟檔案進行讀取。

  • **ReadWrite** - 允許開啟檔案進行讀取和寫入

  • **Write** - 允許開啟檔案進行寫入

讓我們來看一個建立、開啟和讀取檔案內容的示例:

示例

 線上演示

using System;
using System.IO;

namespace FileIOApplication {
   class Program {
      static void Main(string[] args) {
         FileStream F = new FileStream("test.dat", FileMode.OpenOrCreate,
         FileAccess.ReadWrite);
         for (int i = 1; i <= 20; i++) {
            F.WriteByte((byte)i);
         }
         F.Position = 0;
         for (int i = 0; i <= 20; i++) {
            Console.Write(F.ReadByte() + " ");
         }
         F.Close();
         Console.ReadKey();
      }
   }
}

輸出

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 -1

更新於:2020年6月20日

265 次瀏覽

啟動您的職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.