Csharp/C#教程:C#程序中创建、复制、移动、删除文件或文件夹的示例分享

创建文件或文件夹

您可通过编程方式在您的计算机上创建文件夹、子文件夹和子文件夹中的文件,并将数据写入文件。

publicclassCreateFileOrFolder { staticvoidMain() { stringfolderName=@"c:Top-LevelFolder"; stringpathString=System.IO.Path.Combine(folderName,"SubFolder"); stringpathString2=@"c:Top-LevelFolderSubFolder2"; 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-LevelFolderSubFolderttxvauxe.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:UsersPublicTestFolder"; stringtargetPath=@"C:UsersPublicTestFolderSubDir"; //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:UsersPublicpublictest.txt"; stringdestinationFile=@"C:UsersPublicprivatetest.txt"; //Tomoveafileorfoldertoanewlocation: System.IO.File.Move(sourceFile,destinationFile); //Tomoveanentiredirectory.Toprogrammaticallymodifyorcombine //pathstrings,usetheSystem.IO.Pathclass. System.IO.Directory.Move(@"C:UsersPublicpublictest",@"C:UsersPublicprivate"); } }

下面的示例演示如何删除文件和目录。

publicclassSimpleFileDelete { staticvoidMain() { //DeleteafilebyusingFileclassstaticmethod... if(System.IO.File.Exists(@"C:UsersPublicDeleteTesttest.txt")) { //UseatryblocktocatchIOExceptions,to //handlethecaseofthefilealreadybeing //openedbyanotherprocess. try { System.IO.File.Delete(@"C:UsersPublicDeleteTesttest.txt"); } catch(System.IO.IOExceptione) { Console.WriteLine(e.Message); return; } } //...orbyusingFileInfoinstancemethod. System.IO.FileInfofi=newSystem.IO.FileInfo(@"C:UsersPublicDeleteTesttest2.txt"); try { fi.Delete(); } catch(System.IO.IOExceptione) { Console.WriteLine(e.Message); } //Deleteadirectory.Mustbewritableorempty. try { System.IO.Directory.Delete(@"C:UsersPublicDeleteTest"); } catch(System.IO.IOExceptione) { Console.WriteLine(e.Message); } //DeleteadirectoryandallsubdirectorieswithDirectorystaticmethod... if(System.IO.Directory.Exists(@"C:UsersPublicDeleteTest")) { try { System.IO.Directory.Delete(@"C:UsersPublicDeleteTest",true); } catch(System.IO.IOExceptione) { Console.WriteLine(e.Message); } } //...orwithDirectoryInfoinstancemethod. System.IO.DirectoryInfodi=newSystem.IO.DirectoryInfo(@"C:UsersPublicpublic"); //Deletethisdirandallsubdirs. try { di.Delete(true); } catch(System.IO.IOExceptione) { Console.WriteLine(e.Message); } } } 您可能感兴趣的文章:C#下载文件删除文件写入文本的实例C#复制与删除文件的实现方法C#删除只读文件或文件夹(解决File.Delete无法删除文件)C#实现安全删除文件目录的方法C#实现彻底删除文件的方法C#删除文件夹和文件到回收站示例C#删除文件目录或文件的解决方法c#定期删除文件的实操方法

标签: 复制 示例 程序

C语言排序算法之插入排序

如何让C++函数返回值死心塌地为你工作

上述就是C#学习教程:C#程序中创建、复制、移动、删除文件或文件夹的示例分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/cdevelopment/907004.html

(0)
上一篇 2021年10月24日
下一篇 2021年10月24日

精彩推荐