我想使用fileststream将文件从一个文件夹复制到另一个文件夹。如何做到这一点。当我试图使用文件。复制我得到这个文件是由另一个进程使用,为了避免这种情况,我想使用c#使用文件流。谁能提供一个把文件从一个文件夹复制到另一个文件夹的例子?
复制我使用的下面代码:-
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);
}
}
}
您可以使用Stream。CopyTo方法复制文件,如下所示:
public static string CopyFileStream(string outputDirectory, string inputFilePath)
{
FileInfo inputFile = new FileInfo(inputFilePath);
using (FileStream originalFileStream = inputFile.OpenRead())
{
var fileName = Path.GetFileName(inputFile.FullName);
var outputFileName = Path.Combine(outputDirectory, fileName);
using (FileStream outputFileStream = File.Create(outputFileName))
{
originalFileStream.CopyTo(outputFileStream);
}
return outputFileName;
}
}
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);