C#实现拷贝文件到另一个文件夹下

Antonia ·
更新时间:2024-09-20
· 326 次阅读

目录

C#拷贝文件到另一个文件夹下

C#文件搬运(从一个文件夹Copy至另一个文件夹)

总结

C#拷贝文件到另一个文件夹下 /// <summary> /// 拷贝文件到另一个文件夹下 /// </summary> /// <param name="sourceName">源文件路径</param> /// <param name="folderPath">目标路径(目标文件夹)</param> public void CopyToFile(string sourceName, string folderPath) { //例子: //源文件路径 //string sourceName = @"D:\Source\Test.txt"; //目标路径:项目下的NewTest文件夹,(如果没有就创建该文件夹) //string folderPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "NewTest"); if (!Directory.Exists(folderPath)) { Directory.CreateDirectory(folderPath); } //当前文件如果不用新的文件名,那么就用原文件文件名 string fileName = Path.GetFileName(sourceName); //这里可以给文件换个新名字,如下: //string fileName = string.Format("{0}.{1}", "newFileText", "txt"); //目标整体路径 string targetPath = Path.Combine(folderPath, fileName); //Copy到新文件下 FileInfo file = new FileInfo(sourceName); if (file.Exists) { //true 为覆盖已存在的同名文件,false 为不覆盖 file.CopyTo(targetPath, true); } }

注意方法内注释的用法,可以根据自己的需要更改。

C#文件搬运(从一个文件夹Copy至另一个文件夹)

时常我们会遇到文件的复制、上传等问题。特别是自动化生产方面,需要对机台抛出的档案进行搬运、收集,然后对资料里的数据等进行分析,等等。

Winform下,列举集中较常见的档案的搬运。

private void MoveFile() { string Frompath = @"D:\Test\OutPut"; string directoryPath = @"D:\report"; try { string[] picList = Directory.GetFiles(Frompath, "*.jpg"); //图片 string[] txtList = Directory.GetFiles(Frompath, "*.txt"); //文本文件 string[] pdfList = Directory.GetFiles(Frompath, "*.pdf"); //PDF文件 foreach (string f in picList) { //取得文件名. string fName = f.Substring(Frompath.Length + 1); File.Copy(Path.Combine(Frompath, fName), Path.Combine(directoryPath, fName), true); } foreach (string f in txtList) { string fName = f.Substring(Frompath.Length + 1); try { File.Copy(Path.Combine(Frompath, fName), Path.Combine(directoryPath, fName)); } // 捕捉异常. catch (IOException copyError) { MessageBox.Show(copyError.Message); } } foreach (string f in pdfList) { string fName = f.Substring(Frompath.Length + 1); try { File.Copy(System.IO.Path.Combine(Frompath, fName), System.IO.Path.Combine(directoryPath, fName)); } catch (IOException copyError) { MessageBox.Show(copyError.Message); return; } } //删除原始文件夹里的文件 foreach (string f in txtList) { File.Delete(f); } foreach (string f in picList) { File.Delete(f); } foreach (string f in pdfList) { File.Delete(f); } } catch (DirectoryNotFoundException dirNotFound) { MessageBox.Show(dirNotFound.Message); } } 总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持软件开发网。



C# 拷贝

需要 登录 后方可回复, 如果你还没有账号请 注册新账号