C#中如何使用文件流复制文件
How to use filestream for copying files in c#
我想使用 filestream.How 将文件从一个文件夹复制到另一个文件夹,这可以是 achived.when 我尝试使用 file.copy 我得到这个文件正在被另一个进程使用,为了避免这种情况,我想使用 c# 使用文件流。有人可以提供将文件从一个文件夹复制到另一个文件夹的示例吗?
string fileName = "Mytest.txt";
string sourcePath = @"C:\MyTestPath";
string targetPath = @"C:\MyTestTarget";
string sourceFile = System.IO.Path.Combine(sourcePath, fileName);
string destFile = System.IO.Path.Combine(targetPath, fileName);
{
System.IO.Directory.CreateDirectory(targetPath);
}
// To copy a file to another location and
// overwrite the destination file if it already exists.
System.IO.File.Copy(sourceFile, destFile, true);
为了复制,我使用了以下代码:-
public static void Copy(string inputFilePath, string outputFilePath)
{
int bufferSize = 1024 * 1024;
using (FileStream fileStream = new FileStream(outputFilePath, FileMode.OpenOrCreate, FileAccess.Write,FileShare.ReadWrite))
//using (FileStream fs = File.Open(<file-path>, FileMode.Open, FileAccess.Read, FileShare.Read))
{
FileStream fs = new FileStream(inputFilePath, FileMode.Open, FileAccess.ReadWrite);
fileStream.SetLength(fs.Length);
int bytesRead = -1;
byte[] bytes = new byte[bufferSize];
while ((bytesRead = fs.Read(bytes, 0, bufferSize)) > 0)
{
fileStream.Write(bytes, 0, bytesRead);
}
}
}
我想使用 filestream.How 将文件从一个文件夹复制到另一个文件夹,这可以是 achived.when 我尝试使用 file.copy 我得到这个文件正在被另一个进程使用,为了避免这种情况,我想使用 c# 使用文件流。有人可以提供将文件从一个文件夹复制到另一个文件夹的示例吗?
string fileName = "Mytest.txt";
string sourcePath = @"C:\MyTestPath";
string targetPath = @"C:\MyTestTarget";
string sourceFile = System.IO.Path.Combine(sourcePath, fileName);
string destFile = System.IO.Path.Combine(targetPath, fileName);
{
System.IO.Directory.CreateDirectory(targetPath);
}
// To copy a file to another location and
// overwrite the destination file if it already exists.
System.IO.File.Copy(sourceFile, destFile, true);
为了复制,我使用了以下代码:-
public static void Copy(string inputFilePath, string outputFilePath)
{
int bufferSize = 1024 * 1024;
using (FileStream fileStream = new FileStream(outputFilePath, FileMode.OpenOrCreate, FileAccess.Write,FileShare.ReadWrite))
//using (FileStream fs = File.Open(<file-path>, FileMode.Open, FileAccess.Read, FileShare.Read))
{
FileStream fs = new FileStream(inputFilePath, FileMode.Open, FileAccess.ReadWrite);
fileStream.SetLength(fs.Length);
int bytesRead = -1;
byte[] bytes = new byte[bufferSize];
while ((bytesRead = fs.Read(bytes, 0, bufferSize)) > 0)
{
fileStream.Write(bytes, 0, bytesRead);
}
}
}