《C#文件操作大全.pdf》由会员分享,可在线阅读,更多相关《C#文件操作大全.pdf(86页珍藏版)》请在得力文库 - 分享文档赚钱的网站上搜索。
1、C#文件操作大全1.创建文件夹/using System.IO;Directory.CreateDirectory(%1);2.创建文件/using System.IO;File.Create(%l);3.删除文件/using System.IO;File.Delete(%l);4.删除文件夹/using System.IO;Directory.Delete(%1);5.删除一个目录下所有的文件夹/using System.IO;foreach(string dirStr in Directory.GetDirectories(%1)(Directoryinfo dir=new Directo
2、rylnfo(dirStr);ArrayList folders=new ArrayList();FileSystemInfo|fileArr=dir.GetFileSystemlnfos();for(int i=0;i 0)(%2/chunk,chunk.Length)while(chunk.LengthO);fs.Close();)catch(/return-1;8.写入文件/using System.10;Fileinfo f=new Filelnfo(%l);StreamWriter w=f.CreateText();w.WriteLine(%2);w.Flush();w.Close(
3、);9.写入随机文件/using System.IO;byte dataArray=new byte 100000;/new Random().NextB ytes(data Array);using(FileStream FileStream=new FileStream(%l,FileMode.Create)/Write the data to the file,byte by byte.for(int i=0;i dataArray.Length;i+)FileStream.WriteByte(dataArrayi);/Set the stream position to the beg
4、inning of the file.FileStream.Seek(0,SeekOrigin.Begin);/Read and verify the data.for(int i=0;i FileStream.Length;i+)if(dataArrayi!=FileStream.ReadByteO)写入数据错误return;)数据流”+FileStream.Name+”已验证”)10.读取文件属性/using System.IO;Fileinfo f=new FileInfo(%l);/f.CreationTime,f.FullNameif(f.Attributes&FileAttribu
5、tes.ReadOnly)!=0)(%2)else%3)11.写入属性/using System.IO;Fileinfo f=new Filelnfo(%l);设置只读f.Attributes=myFile.Attributes I FileAttributes.ReadOnly;设置可写f.Attributes=myFile.Attributes&-FileAttributes.ReadOnly;12.枚举一个文件夹中的所有文件夹/using System.IO;foreach(string%2 in Directory.GetDirectories(%1)%3Directoryinfo d
6、ir=new Di rectoryl nfo(%1);Filelnfo files=dir.GetFiles(*.*,);foreach(FileInfo%2 in files)%3*/13.复制文件夹/*using System.10;using System.Collections;*/string path=(%2.LastIndexOf(Path.DirectorySeparatorChar)=%2.Length-1)?%2:%2+Path.DirectorySeparatorChar;string parent=Path.GetDirectoryName(%1);Directory.
7、CreateDirectory(path+Path.GetFileName(%l);Directoryinfo dir=new Directorylnfo(%1 .LastIndexOf(Path.DirectorySeparatorChar)=%1.Length-1)?%1:%1+Path.DirectorySeparatorChar);FileSystemInfo fileArr=dir.GetFileSystemlnfos();Queue Folders=new Queue(dir.GetFileSystemInfos();while(Folders.Count0)(FileSystem
8、lnfo tmp=Folders.Dequeue();Fileinfo f=tmp as Fileinfo;if(f=null)(Directoryinfo d=tmp as Directoryinfo;Directory.CreateDirectory(d.FullName.Replace(parent.LastIndexOf(Path.DirectorySeparatorChar)=parent.Length-1)?parent:parent+Path.DirectorySeparatorChar,path);fbreach(FileSystemlnfo fi in d.GetFileSy
9、stemlnfbsO)(Folde rs.Enqueue(fi);)else(f.CopyTo(f.FullName.Replace(parent,path);)14.复制目录下所有的文件夹到另一个文件夹下1*using System.IO;using System.Collections;*/Directoryinfo d=new Directorylnfo(%l);fbreach(Directoryinfo dirs in d.GetDirectories()(Queue al=new Queue(dirs.GetFileSystemInfos();while(al.Count 0)Fil
10、eSystemlnfo temp=al.Dequeue();Fileinfo file=temp as Filelnfb;if(file=null)(Directoryinfo directory=temp as Directoryinfo;Directory.CreateDirectory(path+directory.Name);foreach(FileSystemlnfo fsi in directory.GetFileSystemlnfosO)al.Enqueue(fsi);)elseFile.Copy(file.FullName,path+file.Name);)15.移动文件夹/*
11、using System.IO;using System.Collections;*/string filename=Path.GetFileName(%1);string path=(%2.LastIndexOf(Path.DirectorySeparatorChar)=%2.Length-1)?%2:%2+Path.DirectorySeparatorChar;if(Path.GetPathRoot(%l)=Path.GetPathRoot(%2)Directory.Move(%1,path+filename);else(string parent=Path.GetDirectoryNam
12、e(%1);Directory.CreateDirectory(path+Path.GetFileName(%1);Directoryinfo dir=new Directorylnfo(%l.LastIndexOf(Path.DirectorySeparatorChar)=%1.Length-1)?%1:%1 +Path.DirectorySeparatorChar);FileSystemInfo fileArr=dir.GetFileSystemlnfos();Queue Folders=new Queue(dir.GetFileSystemlnfosO);while(Folders.Co
13、unt 0)(FileSystemlnfo tmp=Fol de rs.Deque ue();Fileinfo f=tmp as Filelnfb;if(f=null)(Directoryinfo d=tmp as Directoryinfo;Directoryinfo dpath=new DirectoryInfo(d.FullName.Replace(parent.LastIndexOf(Path.DirectorySeparatorChar)=parent.Length-1)?parent:parent+Path.DirectorySeparatorChar,path);dpath.Cr
14、eate();foreach(FileSystemlnfo fi in d.GetFileSystemlnfosO)(Folders.Enqueue(fi);elsef.MoveTo(f.FullName.Replace(parent,path);Directory.Delete(%1,true);)16.移动目录下所有的文件夹到另一个目录下/*using System.10;using System.Collections;*/string filename=Path.GetFileName(%1);if(Path.GetPathRoot(%1)=Path.GetPathRoot(%2)fo
15、reach(string dir in Directory.GetDirectories(%l)Directory.Move(dir,Path.Combine(%2,filename);else(foreach(string dir2 in Directory.GetDirectories(%1)(string parent=Path.GetDirectoryName(dir2);Directory.CreateDirectory(Path.Combine(%2,Path.GetFileName(dir2);string dir=(dir2.LastIndexOf(Path.Directory
16、SeparatorChar)=di r2.Length-1)?dir2:dir2+Path.DirectorySeparatorChar;Directoryinfo dirdir=new Directorylnfo(dir);FileSystemInfo fileArr=dirdir.GetFileSystemInfos();Queue Folders=new Queue(dirdir.GetFileSystemlnfos();while(Folders.Count 0)(FileSystemlnfo tmp=Folders.Dequeue();Fileinfo f=tmp as Fileln
17、fb;if(f=null)(Directoryinfo d=tmp as Directoryinfo;Directoryinfo dpath=new DirectoryInfo(d.FullName.Replace(parent.LastIndexOf(Path.DirectorySeparatorChar)=pare nt.Length-1)?parent:parent+Path.DirectorySeparatorChar,%2);dpath.Create();foreach(FileSystemlnfo fi in d.GetFileSystemlnfosO)(Folders.Enque
18、ue(fi);)else(f.M o veTo(f.Full N ame.Re pl ace(paren t,%2);dirdir.Delete(true);17.以一个文件夹的框架在另一个目录创建文件夹和空文件/*using System.10;using System.Collections;*/bool b=false;string path=(%2.LastIndexOf(Path.DirectorySeparatorChar)=%2.Length-1)?%2:%2+Path.DirectorySeparatorChar;string parent=Path.Get Di rector
19、y N ame(%1);Directory.CreateDirectory(path+Path.GetFileName(%l);Directoryinfo dir=new Directorylnfo(%1 .LastIndexOf(Path.DirectorySeparatorChar)=%1.Length-1)?%1:%1+Path.DirectorySeparatorChar);FileSystemlnfo|fileArr=dir.GetFileSystemlnfos();Queue Folders=new Queue(dir.GetFileSystemInfos();while(Fold
20、ers.Count 0)(FileSystemlnfo tmp=Folders.Dequeue();Fileinfo f=tmp as Fileinfo;if(f=null)(Directoryinfo d=tmp as Directoryinfo;Directory.CreateDirectory(d.FullName.Replace(parent.LaslIndexOf(Path.DirectorySeparatorChar)=parent.Length-1)?parent:parent+Path.DirectorySeparatorChar,path);foreach(FileSyste
21、mlnfo fi in d.GetFileSystemlnfosO)(Folders.Enqueue(fi);)else(if(b)File.Create(f.FullName.Replace(parent,path);)18.复制文件/using System.IO;File.Copy(%l,%2);19.复制一个文件夹下所有的文件到另一个目录/using System.10;foreach(string fileStr in Directory.GetFiles(%1)File.Copy(%1 .LastIndexOf(Path.DirectorySeparatorChar)=%1.Len
22、gth 1)?%1+Path.GetFi leN ame(fi le Str):%1+Path.DirectorySeparatorChar+Path.GetFileName(fileStr),(%2.LastIndexOf(Path.DirectorySeparatorChar)=%2.Length-1)?%2+Path.GetFileName(fileStr):%2+Path.DirectorySeparatorChar+Path.GetFileName(fileStr);20.提取扩展名/using System.IO;string%2=Path.GetExtension(%1);21.
23、提取文件名/using System.IO;string%2=Path.GetFileName(%1);22.提取文件路径/using System.IO;string%2=Path.GetDirectoryName(%1);23.替换扩展名/using System.IO;File.ChangeExtension(%1 ,%2);24.追加路径/using System.IO;string%3=Path.Combine(%1 ,%2);25.移动文件/using System.IO;File.Move(%l,%2+Path.DirectorySeparatorChar+file.getnam
24、e(%l);26.移动一个文件夹下所有文件到另一个目录/using System.IO;foreach(string fileStr in Directory.GetFiles(%1)File.Move(%1 .LastIndexOf(Path.DirectorySeparatorChar)=%I.Length-1)?%4-Path.GetFi leN ame(fileStr):%1+Path.DirectorySeparatorChar+Path.GetFileName(fileStr),(%2.LastIndexOf(Path.DirectorySeparatorChar)=%2.Leng
25、th-1)?%2+Path.GetFileName(fileStr):%2+Path.DirectorySeparatorChar+Path.GetFileName(fileStr);27.指定目录下搜索文件/*using System.Text;using System.10;*/string fileName=%1;Drivelnfo|drives=Driveinfo.GetDrives();string parent=Path.Get Di rectory N ame(%2);Directoryinfo dir=new DirectoryInfo(%2.LastIndexOf(Path.
26、DirectorySeparatorChar)=%2.Length-1)?%2:%2+Path.DirectorySeparatorChar);FileSystemInfo fileArr;tryfileArr=di r.Ge tFi leS y ste mln fos();)catch(Exception)(continue;)Queue Folders=new Queue(dir.GetFileSystemInfos();while(Folders.Count 0)(FileSystemlnfo tmp=Folders.Dequeue();Fileinfo f=tmp as Fileinf
27、o;if(f=null)(Directorylnfb d=tmp as Directoryinfo;try(foreach(FileSystemlnfo fi in d.GetFileSystemlnfosO)(Folders.Enqueue(fi);)catch(Exception)else if(f.Name.IndexOf(fileName)-1)(%3=f.FullName;return;)29.文件分割/using System.IO;FileStream fsr=new FileStream(%l,FileMode.Open,FileAccess.Read);byte btArr=
28、new byteffsr.Length;fsr.Read(btArr,0,btArr.Length);fsr.Close();string strFileName=%l.Substring(%l.LastIndexOf(Path.DirectorySeparatorChar)+l);FileStream fsw=new FileStream(%2+strFileName+Hr FileMode.Create,FileAccess.Write);fsw.Write(btArr,0,btArr.Length/2);fsw.Close();fsw=new FileStream(%2+strFileN
29、ame+2 FileMode.Create,FileAccess.Write);fsw.Write(btArr,btArr.Length/2,btArr.Length-btArr.Length/2);fsw.Close();30.文件合并/using System.IO;string strFileName=%1.Substring(%l.LastIndexOf(Path.DirectorySeparatorChar)+1);FileStream fsrl=new FileStream(%2+strFileName+”1 ,FileMode.Open,FileAccess.Read);File
30、Stream fsr2=new FileStream(%2+strFileName+2,FileMode.Open,FileAccess.Read);byte btArr=new byteffsrl.Length+fsr2.Length;fsrl.Read(btArr,0,Convert.ToInt32(fsrl.Length);fsr2.Read(btArr,Convert.ToInt32(fsrl.Length),Convert.ToInt32(fsr2.Length);fsrl.Close();fsr2.Close();FileStream fsw=new FileStream(%2+s
31、trFileName,FileMode.Create,FileAccess.Write);fsw.Write(btArr,0,btArr.Length);fsw.Close();31.文件简单加密/*using System.Windows.Forms;加载 System.Windows.Forms.dll 的.Net APIusing System.IO;using System.Text;*/OpenFileDialog jfc=new OpenFileDialogO;OpenFileDialog jfc2=new OpenFileDialogO;jfc.Filter=可执行文件(*.ex
32、e)l*.exel 压缩文件(*.zip)l*.zip;jfc2.Filter 二”文本文件(*.txt)l*.txt”;if(jfc.ShowDialog()=DialogResult.OK&jfc2.ShowDialog()=DialogResult.OK)(byte sRead=new bytefsr.Length;FileStream fsr=new FileStream(jfc.FileName,fsr.Read(sRead,FileMode.Open,FileAccess.Read);fsr.Read(sRead,O,sRead.Length);fsr.Close();Filein
33、fo f=new Filelnfo(jfc2,FileName);StreamWriter w=f.CreateText();int ka=3,kb=5,kc=2,kd=7,js=0;StringBuilder builder=new StringBuilder(sRead.Length*2);for(int i=O;isRead.Length-1 ;i+=2)(char cl=sReadi;char c2=sReadi+l;int tmp=ka*cl+kc*c2;while(lmp0)tmp+=1024;char sl=tmp%1024;char high=(char)(sl 4)&OxOf
34、);char low=(char)(sl&OxOf);high=high10?(high+0):(high-(char)10+,A,);low=low10?(low+,0*):(low-(char)10+,A,);builder.Append(high);builder.Append(low);tmp=kb*c1+kd*c2;while(tmp0)tmp+=1024;char s2=tmp%1024;high=(char)(s2 4)&OxOf);low=(char)(s2&0 x0f);high=high10?(high+0,):(high-(char)10+A,);low=low 10?(
35、low+,0,):(low-(char)lO+A*);builder.Append(high);builder.Append(low);)if(js=l)(char s3=(sReadsRead.Length-11-4)%1024;char high=(char)(s3 4)&OxOf);char low=(char)(s3&OxOf);high=high10?(high+0,):(high-(char)10+,A,);low=low10?(low+0):(low-(char)10+,A,);builder.Append(high);builder.Append(low);)w.Write(b
36、uilder.ToStringO);w.Flush();w.Close();)32.文件简单解密/using System.IO;FileStream fsr=new FileStream(%l,FileMode.Open,File Access.Read);byte btArr=new bytefsr.Length;fsr.Read(btArr,0,btArr.Length);fsr.Close();for(int i=0;i btArr.Length;i+)int ibt=btArri;ibt-=100;ibt+=256;ibt%=256;btArri=Convert.ToByte(ibt
37、);)string strFileName=Path.GetExtension(%1);FileStream fsw=new FileStream(%2+/+strFileName,FileMode.Create,FileAccess.Write);fsw.Write(btArr,0,btArr.Length);fsw.Close();33.读取ini文件属性/*using System.Runtime.InteropServices;Dlllmport(kernel32)private static extern long GetPrivateProfileString(string sec
38、tion,string key,string def,StringBuilder retVal,int size,stringfilePath);*/string Section=%1;string Key=%2;string NoText=%3;string iniFilePath=%4;/,Setup.iniMstring%4=String.Empty;if(File.Exists(iniFilePath)StringBuilder temp=new StringBuilder(1024);GetPrivateProfileString(Section,Key,NoText,temp J
39、024,iniFilePath);%4=temp.ToString();)34.合并一个目录下所有的文件/using System.IO;FileStream fsw=new FileStream(%2,FileMode.Create,File Access.Write);foreach(string fileStr in Directory.GetFiles(%1)(FileStream fsrl=new FileStream(fileStr,FileMode.Open,FileAccess.Read);byte11 btArr=new bytefsrl.Length;fsrl.Read(b
40、tArr,0,Convert.ToInt32(fsrl.Length);fsrl.Close();fsw.Write(btArr,0,btArr.Length);)fsw.Close();35.写入ini文件属性/*using System.Runtime.InteropServices;Dlllmport(”kernel32)返回0 表示失败,非 0 为成功private static extern long WritePrivateProfileString(string section,string key,string val,string filePath);*/string Sec
41、tion=%1;string Key=%2;string Value=%3;string iniFilePath=%4;/Setup.inibool%4=false;if(File.Exists(iniFilePath)(long OpStation=WritePrivateProfileString(Section,Key,Value,iniFilePath);if(OpStation=0)(%4=false;)else(%4=true;)36.获得当前路径string%l=Environment.CurrentDirectory;37.读取XML数据库/using System.Xml;X
42、mlDocument doc=new XmlDocument();doc.Load(%l);string%9;XmlElement xe=doc.GetElementByld(%7);XmlNodeList elemList=xe.ChildNodes;fore ach(X mlN ode elem in elemList)(if(elem.NodeType=%8)(%9=elem.Value;break;38.写入XML数据库/using System.Xml;XmlDocument doc=new XmlDocument();doc.Load(%l);XmlNode root=doc.Do
43、cumentElement;XmlElement book=doc.CreateElement(%3);XmlElement book=doc.CreateElement(%5);XmlElement port=doc.CreateElement(%6);book.SetAttribute(%4,root.ChildNodes.Count.ToString();author.InnerText=%8;book.appendChild(author);book.appendChild(port);root.appendChild(book);doc.Save(%l);39.ZIP压缩文件/*us
44、ing System.10;using System.lO.Compression;*/FileStream infile;try(/Open the file as a FileStream object.infile=new FileStream(%1,FileMode.Open,FileAccess.Read,FileShare.Read);byte buffer=new byteinfile.LengthJ;/Read the file to ensure it is readable.int count=infile.Read(buffer,0,buffer.Length);if(c
45、ount!=buffer.Length)infile.Close();/Test Failed:Unable to read data from filereturn;)infile.Close();MemoryStream ms=new MemoryStream();/Use the newly created memory stream for the compressed data.DellateStream compressedzipStream=new DeflateStream(ms,CompressionMode.Compress,true);/Compressioncompre
46、ssedzipStream.Write(buffer,0,buffer.Length);/Close the pressedzipStream.Close();/Original size:0,Compressed size:1 buffer.Length,ms.Length);Fileinfo f=new Filelnfo(%2);StreamWriter w=f.CreateText();w.Write(buffer,O,ms.Length);w.Close();/end trycatch(InvalidDataException)(/Erro亡 The file being read c
47、ontains invalid data.)catch(FileNotFoundException)(/Error:The file specified was not found.catch(ArgumentException)(/Error:path is a zero-length string,contains only white space,or contains one or more invalid characters catch(PathTooLongException)(/Error:The specified path,file name,or both exceed
48、the system-defined maximum length.For example,onWindows-basedplatforms,paths must be less than 248 characters,and file names must be less than 260 characters.catch(DirectoryNotFoundException)(/Error:The specified path is invalid,such as being on an unmapped drive.catch(lOException)(/Error:An I/O err
49、or occurred while opening the file.catch(UnauthorizedAccessExcepti on)(/Error:path specified a file that is read-only,the path is a directory,or caller does not have the requiredpermissions.catch(IndexOutOfRangeException)/Error:You must provide parameters for MyGZIP.40.ZIP解压缩/*using System.10;using
50、System.IO.Compression;*/FileStream infile;try(/Open the file as a FileStream object,infile=new FileStream(%l,FileMode.Open,FileAccess.Read,FileShare.Read);byte buffer=new byteinfile.Length;/Read the file to ensure it is readable.int count=infile.Read(buffer,0,buffer.Length);if(count!=buffer.Length)(