Lập trình C# - Sao chép file
Sao chép file
Viết chương trình C# để sao chép nội dung từ file này sang file khác.
Chương trình C#
Dưới đây là chương trình C# minh họa lời giải cho bài tập sao chép file trong C#. Bạn cần sử dụng System.IO namespace cho hoạt động đọc ghi file.
using System;
using System.IO;
namespace Csharp
{
class TestCsharp
{
static void Main(string[] args)
{
Console.WriteLine("\nSao chep file trong C#:");
Console.WriteLine("--------------------------\n");
const int BUFFER_SIZE = 512 * 1024;
byte[] data = new byte[BUFFER_SIZE];
FileStream inFile = File.OpenRead("test.txt");
FileStream outFile = File.Create("test2.txt");
int amountRead;
do
{
amountRead = inFile.Read(data, 0, BUFFER_SIZE);
outFile.Write(data, 0, amountRead);
}
while (amountRead == BUFFER_SIZE);
inFile.Close();
outFile.Close();
Console.ReadKey();
}
}
}
Biên dịch và chạy chương trình C# trên sẽ cho kết quả:
Giả sử, nội dung của test.txt như sau: (được tạo trong các bài tập trước)
Khi đó, nội dung của test2.txt sẽ như sau: