用 C# 將流寫入檔案
Muhammad Maisam Abbas
2024年2月16日

本教程將討論使用 C# 將流寫入檔案的方法。
在 C# 中使用 Stream.CopyTo()
方法將流寫入檔案
C# 中的 Stream.CopyTo()
方法將流的內容複製到另一個流。我們可以在第二個流中開啟一個檔案,然後使用 C# 中的 Stream.CopyTo()
方法將輸入流的內容複製到輸出流。
using System;
using System.IO;
namespace read_integer {
class Program {
static void Main(string[] args) {
using (Stream inStream = File.OpenRead(@"C:\File\file.txt")) {
using (Stream outStream = File.OpenWrite(@"C:\File\file1.txt")) {
inStream.CopyTo(outStream);
}
}
}
}
}
在上面的程式碼中,我們使用 C# 中的 inStream.CopyTo(outStream)
方法將輸入流 inStream
的內容寫入輸出流 outStream
。我們首先開啟路徑 C:\File
內的輸入檔案 file.txt
,以將資料讀取到 inStream
流中。之後,我們在相同目錄 C:\File
內開啟輸出檔案 file1.txt
,並使用 outStream
流進行寫入。然後,使用 Stream.CopyTo()
方法將 inStream
的內容寫入 outStream
。
Maisam is a highly skilled and motivated Data Scientist. He has over 4 years of experience with Python programming language. He loves solving complex problems and sharing his results on the internet.
LinkedIn