最近遇一个问题,一个程序调用另一个程序的文件,结果另一个程序的文件被占用,使用不了文件。这时候的解决方案就是把另一个程序的文件拷贝到当前程序就可以了。本文介绍用C#拷贝文件的三种方式。
1、Copy
这个是C#比较常用的拷贝文件方法,是File下面的一个方法,这种适用于没有特殊要求的文件拷贝,使用方法如下:.
string sourceFile = @"c:\temp\test001.txt";string tagretFile = @"c:\temp\test003.txt";if (!Directory.Exists(@"c:\temp"))//需要判断文件夹是否存在Directory.CreateDirectory(path);// 如果等于true则覆盖目标目录文件,否则不覆盖bool isrewrite=true;System.IO.File.Copy(sourcePath, targetPath, isrewrite);
2、CopyTo
如果你有更比较高级的需要可以考虑使用CopyTo的方式拷贝文件,CopyTo 方法可以返回一个 FileInfo 类型,表示复制操作后的新文件信息;而且CopyTo 支持不同的文件系统中复制文件;CopyTo 方法可以使用 FileOptions 枚举来指定操作行为,例如指定是否覆盖目标文件、是否允许在复制期间绕过缓存等等。
string sourceFile = @"c:\temp\test001.txt";string tagretFile = @"c:\temp\test003.txt";FileInfo file = new FileInfo(sourceFile);if (file.Exists) //可以判断源文件是否存在{// 这里是true的话覆盖file.CopyTo(tagretFile , true);}
3、使用文件流读写来实现Copy
如果你有更高的需求,可以使用文件流的方式来拷贝,代码如下:
uing System.IO;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);}}}}//调用方法#regionstring sourceFile = @"e:\temp\test001.txt";string tagretFile = @"e:\temp\test003.txt";CopyFileUsingFileStream(sourceFile, tagretFile);#endregion
