C#文件拷贝的方法

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);
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

大浪淘沙胡

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值