1、实现功能:打开的文件夹如果和目标文件夹不一样,则将文件拷贝到目标文件夹
string filename;
string path;
OpenFileDialog ofd = new OpenFileDialog();
string targetPath = $"{AppDomain.CurrentDomain.BaseDirectory}help\\";
ofd.InitialDirectory = targetPath;
ofd.Filter = "PDF文件(*.pdf)|*.pdf";
ofd.RestoreDirectory = true ;
if (ofd.ShowDialog() == true)
{
//文件全名
filename = ofd.FileName ;
//文件路径
path = System.IO.Path.GetDirectoryName(filename);
//文件名
string name =System.IO.Path.GetFileName(filename);
if (!path.Equals(targetPath))
{
if (!Directory.Exists(targetPath))
{
Directory.CreateDirectory(targetPath);
}
string targrtFile = System.IO.Path.Combine(targetPath, name);
System.IO.File.Copy(filename, targrtFile,true);
}
}
2、文件拷贝方法一(Copy)
stringsourceFile=@"c:\temp\testSource.txt";
stringtagretFile=@"c:\temp\testTarget.txt";
//需要判断文件夹是否存在
if(!Directory.Exists(@"c:\temp")){
Directory.CreateDirectory(path);
}
//如果isrewrite等于true则覆盖目标目录文件,否则不覆盖
System.IO.File.Copy(sourcePath, targetPath, isrewrite);
3、文件拷贝方法二(CopyTo)
string sourceFile = @"c:\temp\testSource.txt";
string tagretFile = @"c:\temp\testTarget.txt";
FileInfo file = new FileInfo(sourceFile);
//可以判断源文件是否存在
if (file.Exists)
{
// 为true则覆盖
file.CopyTo(tagretFile , true);
}
4、文件拷贝方法三(文件流)
创建拷贝函数
public static void CopyFileUsingFileStream(string sourceFilePath, string destFilePath)
{
// 创建读文件流并读取文件
using (FileStream sourceStream = new FileStream(sourceFilePath, FileMode.Open))
{
// 创建写文件流并写入
using (FileStream destStream = new FileStream(destFilePath, FileMode.Create))
{
// 创建一个缓冲区来存储读取的数据
byte[] buffer = new byte[1024];
// 读取数据写入到目标文件流
int bytesRead;
while ((bytesRead = sourceStream.Read(buffer, 0, buffer.Length)) > 0)
{
destStream.Write(buffer, 0, bytesRead);
}
}
}
}
调用拷贝函数
string sourceFile = @"e:\temp\testSource.txt";
string tagretFile = @"e:\temp\testTarget.txt";
CopyFileUsingFileStream(sourceFile, tagretFile);