將陣列寫入檔案中的 C# 程式


使用 WriteAllLines 方法將陣列寫入檔案。

首先,設定一個字串陣列 −

string[] stringArray = new string[] {
   "one",
   "two",
   "three"
};

現在,使用 WriteAllLines 方法將上述陣列新增到檔案 −

File.WriteAllLines("new.txt", stringArray);

以下是完整程式碼 −

示例

 線上演示

using System.IO;
using System;
public class Program {
   public static void Main() {
      string[] stringArray = new string[] {
         "one",
         "two",
         "three"
      };
      File.WriteAllLines("new.txt", stringArray);
      using (StreamReader sr = new StreamReader("new.txt")) {
         string res = sr.ReadToEnd();
         Console.WriteLine(res);
      }
   }
}

輸出

one
two
three

更新時間: 22-Jun-2020

4K+ 檢視

開啟您的 職業之路

透過完成課程獲得認證

開始
廣告