
C#でファイルをコピーする方法はいくつかあります。以下にいくつかの方法を示します。
FileクラスのCopyメソッドを使用する方法
string sourceFilePath = "C:\source\file.txt";
string destinationFilePath = "C:\destination\file.txt";
File.Copy(sourceFilePath, destinationFilePath);
この方法では、FileクラスのCopyメソッドを使用して、ソースファイルのパスとコピー先のパスを指定します。
FileInfoクラスを使用する方法
string sourceFilePath = "C:\source\file.txt";
string destinationFilePath = "C:\destination\file.txt";
FileInfo file = new FileInfo(sourceFilePath);
file.CopyTo(destinationFilePath);
FileInfoクラスを使用すると、ファイルに関する詳細な情報を取得することができます。CopyToメソッドを使用してファイルをコピーします。
StreamReaderとStreamWriterを使用する方法
string sourceFilePath = "C:\source\file.txt";
string destinationFilePath = "C:\destination\file.txt";
using (StreamReader reader = new StreamReader(sourceFilePath))
{
using (StreamWriter writer = new StreamWriter(destinationFilePath))
{
writer.Write(reader.ReadToEnd());
}
}
この方法では、StreamReaderとStreamWriterを使用してファイルの内容を読み取り、コピー先に書き込みます。
FileStreamを使用する方法:
string sourceFilePath = "C:\source\file.txt";
string destinationFilePath = "C:\destination\file.txt";
using (FileStream sourceStream = new FileStream(sourceFilePath, FileMode.Open))
{
using (FileStream destinationStream = new FileStream(destinationFilePath, FileMode.Create))
{
sourceStream.CopyTo(destinationStream);
}
}
この方法では、FileStreamを使用してファイルのバイナリデータを読み取り、コピー先に書き込みます。
これらは一部の一般的な方法ですが、ファイルコピーに関するさまざまなオプションや制約があります。コピーするファイルの種類やサイズ、目的に応じて、最適な方法を選択してください。
関連記事
