C# 中的流数组

csharpprogrammingserver side programming更新于 2025/9/20 4:38:00

为值 − 设置字符串数组

string[] names = new string[] {"Jack", "Tom"};

现在使用 foreach 数组,将内容写入文件 −

using (StreamWriter sw = new StreamWriter("names.txt")) {

   foreach (string s in names) {
      sw.WriteLine(s);
   }
}

以下是显示将文本写入文件的流数组的示例 −

示例

using System;
using System.IO;

namespace FileApplication {
   class Program {
      static void Main(string[] args) {
          string[] names = new string[] {"Jack", "Tom"};

         using (StreamWriter sw = new StreamWriter("names.txt")) {

            foreach (string s in names) {
               sw.WriteLine(s);
            }
           }

         // 读取并显示文件中的每一行。
         string line = "";
         using (StreamReader sr = new StreamReader("names.txt")) {
            while ((line = sr.ReadLine()) != null) {
               Console.WriteLine(line);
            }
         }
         Console.ReadKey();
      }
   }
}

相关文章