日期:2014-05-17  浏览次数:20820 次

C#中常用的经典文件操作方法

C#追加文件
StreamWriter sw = File.AppendText(Server.MapPath(".")+"\\myText.txt");
sw.WriteLine("追逐理想");
sw.WriteLine("kzlll");
sw.WriteLine(".NET笔记");
sw.Flush();
sw.Close();

C#拷贝文件stringOrignFile,NewFile;
rignFile = Server.MapPath(".")+"\\myText.txt";
NewFile = Server.MapPath(".")+"\\myTextCopy.txt";
File.Copy(OrignFile,NewFile,true);

C#删除文件stringdelFile = Server.MapPath(".")+"\\myTextCopy.txt";
File.Delete(delFile);

C#移动文件stringOrignFile,NewFile;
rignFile = Server.MapPath(".")+"\\myText.txt";
NewFile = Server.MapPath(".")+"\\myTextCopy.txt";
File.Move(OrignFile,NewFile);

C#创建目录// 创建目录c:\sixAgeDirectoryInfo d=Directory.CreateDirectory("c:\\sixAge");// d1指向c:\sixAge\sixAge1DirectoryInfo d1=d.CreateSubdirectory("sixAge1");// d2指向c:\sixAge\sixAge1\sixAge1_1DirectoryInfo d2=d1.CreateSubdirectory("sixAge1_1");// 将当前目录设为c:\sixAgeDirectory.SetCurrentDirectory("c:\\sixAge");// 创建目录c:\sixAge\sixAge2Directory.CreateDirectory("sixAge2");// 创建目录c:\sixAge\sixAge2\sixAge2_1Directory.CreateDirectory("sixAge2\\sixAge2_1");

递归删除文件夹及文件publicvoidDeleteFolder(stringdir)
{if(Directory.Exists(dir))//如果存在这个文件夹删除之{foreach(stringdinDirectory.GetFileSystemEntries(dir)) {if(File.Exists(d))
??????????????? File.Delete(d);//直接删除其中的文件elseDeleteFolder(d);//递归删除子文件夹}
??????? Directory.Delete(dir);//删除已空文件夹Response.Write(dir+" 文件夹删除成功");
??? }elseResponse.Write(dir+" 该文件夹不存在");//如果文件夹不存在则提示}protectedvoidPage_Load (Objectsender ,EventArgs e)
{stringDir="D:\\gbook\\11";
??? DeleteFolder(Dir);//调用函数删除文件夹}// ======================================================