C#實現(xiàn)拷貝文件到另一個文件夾下
更新時間:2023年01月25日 15:24:38 作者:熊思宇
這篇文章主要介紹了C#實現(xiàn)拷貝文件到另一個文件夾下,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
C#拷貝文件到另一個文件夾下
/// <summary> /// 拷貝文件到另一個文件夾下 /// </summary> /// <param name="sourceName">源文件路徑</param> /// <param name="folderPath">目標(biāo)路徑(目標(biāo)文件夾)</param> public void CopyToFile(string sourceName, string folderPath) { //例子: //源文件路徑 //string sourceName = @"D:\Source\Test.txt"; //目標(biāo)路徑:項目下的NewTest文件夾,(如果沒有就創(chuàng)建該文件夾) //string folderPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "NewTest"); if (!Directory.Exists(folderPath)) { Directory.CreateDirectory(folderPath); } //當(dāng)前文件如果不用新的文件名,那么就用原文件文件名 string fileName = Path.GetFileName(sourceName); //這里可以給文件換個新名字,如下: //string fileName = string.Format("{0}.{1}", "newFileText", "txt"); //目標(biāo)整體路徑 string targetPath = Path.Combine(folderPath, fileName); //Copy到新文件下 FileInfo file = new FileInfo(sourceName); if (file.Exists) { //true 為覆蓋已存在的同名文件,false 為不覆蓋 file.CopyTo(targetPath, true); } }
注意方法內(nèi)注釋的用法,可以根據(jù)自己的需要更改。
C#文件搬運(yùn)(從一個文件夾Copy至另一個文件夾)
時常我們會遇到文件的復(fù)制、上傳等問題。特別是自動化生產(chǎn)方面,需要對機(jī)臺拋出的檔案進(jìn)行搬運(yùn)、收集,然后對資料里的數(shù)據(jù)等進(jìn)行分析,等等。
Winform下,列舉集中較常見的檔案的搬運(yùn)。
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); } }
總結(jié)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
C#中將DataTable轉(zhuǎn)換成CSV文件的方法
DataTable用于在.net項目中,用于緩存數(shù)據(jù),DataTable表示內(nèi)存中數(shù)據(jù)的一個表,在.net項目中運(yùn)用C#將DataTable轉(zhuǎn)化為CSV文件,接下來通過本文給大家提供一個通用的方法,感興趣的朋友可以參考下2016-10-10Windows系統(tǒng)中C#調(diào)用WinRAR來壓縮和解壓縮文件的方法
這篇文章主要介紹了Windows系統(tǒng)中C#調(diào)用WinRAR來壓縮和解壓縮文件的方法,個人感覺在Windows中WinRAR相對7-zip更加穩(wěn)定一些,需要的朋友可以參考下2016-04-04