C#程序中创建、复制、移动、删除文件或文件夹的示例
创建文件或文件夹
您可通过编程方式在您的计算机上创建文件夹、子文件夹和子文件夹中的文件,并将数据写入文件。
publicclassCreateFileOrFolder { staticvoidMain() { stringfolderName=@"c:\Top-LevelFolder"; stringpathString=System.IO.Path.Combine(folderName,"SubFolder"); stringpathString2=@"c:\Top-LevelFolder\SubFolder2"; System.IO.Directory.CreateDirectory(pathString); stringfileName=System.IO.Path.GetRandomFileName(); pathString=System.IO.Path.Combine(pathString,fileName); Console.WriteLine("Pathtomyfile:{0}\n",pathString); if(!System.IO.File.Exists(pathString)) { using(System.IO.FileStreamfs=System.IO.File.Create(pathString)) { for(bytei=0;i<100;i++) { fs.WriteByte(i); } } } else { Console.WriteLine("File\"{0}\"alreadyexists.",fileName); return; } try { byte[]readBuffer=System.IO.File.ReadAllBytes(pathString); foreach(bytebinreadBuffer) { Console.Write(b+""); } Console.WriteLine(); } catch(System.IO.IOExceptione) { Console.WriteLine(e.Message); } System.Console.WriteLine("Pressanykeytoexit."); System.Console.ReadKey(); } }
输出:
Pathtomyfile:c:\Top-LevelFolder\SubFolder\ttxvauxe.vv0
01234567891011121314151617181920212223242526272829 303132333435363738394041424344454647484950515253545556 57585960616263646566676869707172737475767778798081828 384858687888990919293949596979899
如果该文件夹已存在,则CreateDirectory不执行任何操作,且不会引发异常。但是,File.Create用新的文件替换现有文件。该示例使用一个if-else语句阻止现有文件被替换。
通过在示例中做出以下更改,您可以根据具有某个名称的程序是否存在来指定不同的结果。如果该文件不存在,代码将创建一个文件。如果该文件存在,代码将把数据添加到该文件中。
指定一个非随机文件名。
//Commentoutthefollowingline. //stringfileName=System.IO.Path.GetRandomFileName(); //Replacethatlinewiththefollowingassignment. stringfileName="MyNewFile.txt";
用以下代码中的using语句替换if-else语句。
using(System.IO.FileStreamfs=newSystem.IO.FileStream(pathString,FileMode.Append)) { for(bytei=0;i<100;i++) { fs.WriteByte(i); } }
运行该示例若干次以验证数据是否每次都添加到文件中。
复制、删除和移动文件和文件夹
以下示例说明如何使用System.IO命名空间中的System.IO.File、System.IO.Directory、System.IO.FileInfo和System.IO.DirectoryInfo类以同步方式复制、移动和删除文件和文件夹。这些示例没有提供进度栏或其他任何用户界面。
。
示例
下面的示例演示如何复制文件和目录。
publicclassSimpleFileCopy { staticvoidMain() { stringfileName="test.txt"; stringsourcePath=@"C:\Users\Public\TestFolder"; stringtargetPath=@"C:\Users\Public\TestFolder\SubDir"; //UsePathclasstomanipulatefileanddirectorypaths. stringsourceFile=System.IO.Path.Combine(sourcePath,fileName); stringdestFile=System.IO.Path.Combine(targetPath,fileName); //Tocopyafolder'scontentstoanewlocation: //Createanewtargetfolder,ifnecessary. if(!System.IO.Directory.Exists(targetPath)) { System.IO.Directory.CreateDirectory(targetPath); } //Tocopyafiletoanotherlocationand //overwritethedestinationfileifitalreadyexists. System.IO.File.Copy(sourceFile,destFile,true); //Tocopyallthefilesinonedirectorytoanotherdirectory. //Getthefilesinthesourcefolder.(Torecursivelyiteratethrough //allsubfoldersunderthecurrentdirectory,see //"Howto:IterateThroughaDirectoryTree.") //Note:Checkfortargetpathwasperformedpreviously //inthiscodeexample. if(System.IO.Directory.Exists(sourcePath)) { string[]files=System.IO.Directory.GetFiles(sourcePath); //Copythefilesandoverwritedestinationfilesiftheyalreadyexist. foreach(stringsinfiles) { //UsestaticPathmethodstoextractonlythefilenamefromthepath. fileName=System.IO.Path.GetFileName(s); destFile=System.IO.Path.Combine(targetPath,fileName); System.IO.File.Copy(s,destFile,true); } } else { Console.WriteLine("Sourcepathdoesnotexist!"); } //Keepconsolewindowopenindebugmode. Console.WriteLine("Pressanykeytoexit."); Console.ReadKey(); } }
下面的示例演示如何移动文件和目录。
publicclassSimpleFileMove { staticvoidMain() { stringsourceFile=@"C:\Users\Public\public\test.txt"; stringdestinationFile=@"C:\Users\Public\private\test.txt"; //Tomoveafileorfoldertoanewlocation: System.IO.File.Move(sourceFile,destinationFile); //Tomoveanentiredirectory.Toprogrammaticallymodifyorcombine //pathstrings,usetheSystem.IO.Pathclass. System.IO.Directory.Move(@"C:\Users\Public\public\test\",@"C:\Users\Public\private"); } }
下面的示例演示如何删除文件和目录。
publicclassSimpleFileDelete { staticvoidMain() { //DeleteafilebyusingFileclassstaticmethod... if(System.IO.File.Exists(@"C:\Users\Public\DeleteTest\test.txt")) { //UseatryblocktocatchIOExceptions,to //handlethecaseofthefilealreadybeing //openedbyanotherprocess. try { System.IO.File.Delete(@"C:\Users\Public\DeleteTest\test.txt"); } catch(System.IO.IOExceptione) { Console.WriteLine(e.Message); return; } } //...orbyusingFileInfoinstancemethod. System.IO.FileInfofi=newSystem.IO.FileInfo(@"C:\Users\Public\DeleteTest\test2.txt"); try { fi.Delete(); } catch(System.IO.IOExceptione) { Console.WriteLine(e.Message); } //Deleteadirectory.Mustbewritableorempty. try { System.IO.Directory.Delete(@"C:\Users\Public\DeleteTest"); } catch(System.IO.IOExceptione) { Console.WriteLine(e.Message); } //DeleteadirectoryandallsubdirectorieswithDirectorystaticmethod... if(System.IO.Directory.Exists(@"C:\Users\Public\DeleteTest")) { try { System.IO.Directory.Delete(@"C:\Users\Public\DeleteTest",true); } catch(System.IO.IOExceptione) { Console.WriteLine(e.Message); } } //...orwithDirectoryInfoinstancemethod. System.IO.DirectoryInfodi=newSystem.IO.DirectoryInfo(@"C:\Users\Public\public"); //Deletethisdirandallsubdirs. try { di.Delete(true); } catch(System.IO.IOExceptione) { Console.WriteLine(e.Message); } } }