c#文件操作.pdf

上传人:奔*** 文档编号:89833960 上传时间:2023-05-13 格式:PDF 页数:133 大小:11.63MB
返回 下载 相关 举报
c#文件操作.pdf_第1页
第1页 / 共133页
c#文件操作.pdf_第2页
第2页 / 共133页
点击查看更多>>
资源描述

《c#文件操作.pdf》由会员分享,可在线阅读,更多相关《c#文件操作.pdf(133页珍藏版)》请在得力文库 - 分享文档赚钱的网站上搜索。

1、1.创 建 文 件 夹/using System.IO;Directory.CreateDirectory(%1);2.创 建 文 件/using System.IO;File.Create(%1);3.删 除 文 件/using System.IO;File.Delete(%1);4.删 除 文 件 夹/using System.IO;Directory.Delete(%1);5.删 除 个 目 录 下 所 有 的 文 件 夹/using System.IO;foreach(string dirStr in Directory.GetDirectories(%1)(Di rectory In

2、fo dir=new Directorylnfo(dirStr);ArrayList folders=new ArrayList();FileSystemlnfo fileArr=dir.GetFileSystemlnfos();for(int i=0;i folders.Count;i+)Fileinfo f=foldersi as Fileinfo;if(f=null)Directoryinfo d=foldersi as Di rectory Info;d.Delete();)6.清 空 文 件 夹/using System.IO;Directory.Delete(%1,true);Di

3、rectory.CreateDirectory(%1);7.读 取 文 件/using System.IO;StreamReader s=File.OpenText(%1);string%2=null;while(%2=s.ReadLine()!=null)%3s.Close();8.写 入 文 件/using System.IO;Fileinfo f=new Filelnfo(%1);Stream Writer w=f.CreateText();w.WriteLine(%2);w.Close();9.写 入 随 机 文 件/using System.IO;byte dataArray=new

4、 byte100000y/new Random().NextBytes(dataArray);using(FileStream FileStream=new FileStream(%1,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 beginning of the file.FileStream.Seek(0,SeekOrigin

5、.Begin);/Read and verify the data.for(int i=0;i FileStream.Length;i+)if(dataArrayi!=FileStream.ReadByte()写 入 数 据 错 误 return;)数 据 流+FileStream.Name+”已 验 证”)10.读 取 文 件 属 性/using System.IO;Fileinfo f=new Filelnfo(%1);/f.CreationTimeJf.FullNameif(f.Attributes&FileAttributes.Readonly)!=0)%2else%3)11.写 入

6、属 性/using System.IO;Fileinfo f=new Filelnfo(%1);设 置 只 读(.Attributes=myFile.Attributes|FileAttributes.Readonly;设 置 可 写(.Attributes=myFile.Attributes&-FileAttributes.Readonly;12.枚 举 个 文 件 夹 中 的 所 有 文 件 夹/using System.IO;foreach(string%2 in Directory.GetDirectories(%1)%3)/*Directoryinfo dir=new Directo

7、rylnfo(%1);Filelnfo files=dir.GetFilesC*.*);foreach(Filelnfo%2 in files)%3713.复 制 文 件 夹 using System.IO;using System.Collections;*/string path=(%2.LastlndexOf()=%2.Length-1)?%2:%2+“;string parent=Path.GetDirectoryName(%1);Directory.CreateDirectory(path+Path.GetFileName(%1);Directoryinfo dir=new Dire

8、ctorylnfo(%1.LastlndexOf(H)=%1.Length-1)?%1:%1+M);FileSystemlnfo fileArr=dir.GetFileSystemlnfos();Queue Folders=new Queue(dir.GetFileSystemlnfos();while(Folders.Count0)FileSystemlnfo tmp=Folders.Dequeue();Fileinfo f=tmp as Fileinfo;if(f=null)(Directoryinfo d=tmp as Directoryinfo;Directory.CreateDire

9、ctory(d.FullName.Replace(parent.LastlndexOf(H)=parent.Length-1)?parent:parent+path);foreach(FileSystemlnfo fi in d.GetFile8ystemlnfos()(Folders.Enqueue(fi);)else(f.CopyTo(f.FullName.Replace(parent,path);)14.复 制 目 录 卜.所 有 的 文 件 夹 到 另 个 文 件 夹 下using System.10;using System.Collections;7Directoryinfo d=

10、new Directorylnfo(%1);foreach(Directoryinfo dirs in d.GetDirectories()Queue al=new Queue(dirs.GetFileSystemlnfos();while(al.Count 0)FileSystemlnfo temp=al.Dequeue();Fileinfo file=temp as Fileinfo;if(file=null)(Directoryinfo directory=temp as Directoryinfo;Directory.CreateDirectory(path+directory.Nam

11、e);foreach(FileSystemlnfo fsi in directory.GetFileSystemlnfos()al.Enqueue(fsi);)elseFile.Copy(file.FullName,path+file.Name);)15.移 动 文 件 夹/*using System.IO;using System.Collections;7string filename=Path.GetFileName(%1);string path=(%2.LastlndexOf(V)=%2.Length-1)?%2:%2+“;if(Path.GetPathRoot(%1)=Path.G

12、etPathRoot(%2)Di rectory.Move(%1,path+filename);elsestring parent=Path.GetDirectoryName(%1);Directory.CreateDirectory(path+Path.GetFileName(%1);Directoryinfo dir=new Directory I nfo(%1.LastlndexOf()=%1.Length-1)?%1:%1+”);FileSystemlnfof fileArr=dir.GetFileSystemlnfos();Queue Folders=new Queue(dir.Ge

13、tFileSystemlnfos();while(Folders.Count 0)(FileSystemlnfo tmp=Folders.Dequeue();Fileinfo f=tmp as Fileinfo;if(f=null)(Directoryinfo d=tmp as Directoryinfo;Directoryinfo dpath=new Directorylnfo(d.FullName.Replace(parent.LastlndexOf(M)=parent.Length-1)?parent:parent+path);dpath.Create();foreach(FileSys

14、temlnfo fi in d.GetFileSystemlnfos()(Folders.Enqueue(fi);)else(f.MoveTo(f.FullName.Replace(parent,path);)Directory.Delete(%1,true);)16.移 动 目 录 下 所 有 的 文 件 夹 到 另 一 个 目 录 下 using System.IO;using System.Collections;7string filename=Path.GetFileName(%1);if(Path.GetPathRoot(%1)=Path.GetPathRoot(%2)foreac

15、h(string dir in Directory.GetDirectories(%1)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.LastlndexOf(”)=dir2.Length-1)?

16、dir2:dir2+“;Directoryinfo dirdir=new DirectoryInfo(dir);FileSystemlnfo fileArr=dirdir.GetFileSystemlnfos();Queue Folders=newQueue(dirdir.GetFileSystemlnfos();while(Folders.Count 0)(FileSystemlnfo tmp=Folders.Dequeue();Fileinfo f=tmp as Fileinfo;if(f=null)(Directoryinfo d=tmp as Directoryinfo;Di rect

17、ory Info dpath=newDirectorylnfo(d.FullName.Replace(parent.LastlndexOf()=parent.Length-1)?parent:parent+%2);dpath.Create();foreach(FileSystemlnfo fi in d.GetFileSystemlnfos()Folders.Enqueue(fi);)else(f.MoveTo(f.FullName.Replace(parent,%2);)dirdir.Delete(true);)17.以 个 文 件 夹 的 框 架 在 另 个 目 录 创 建 文 件 夹 和

18、 空 文 件/*using System.I0;using System.Collections;7bool b=false;string path=(%2.LastlndexOf(V)=%2.Length-1)?%2:%2+string parent=Path.GetDirectoryName(%1);Directory.CreateDirectory(path+Path.GetFileName(%1);Directoryinfo dir=new Directorylnfo(%1.LastlndexOf(w)=%1.Length-1)?%1:%1+W);FileSystemlnfo file

19、Arr=dir.GetFileSystemlnfos();Queue Folders=new Queue(dir.GetFileSystemlnfos();while(Folders.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.LastlndexOf()=parent.Length-1)?parent

20、:parent+AV,path);foreach(FileSystemlnfo fi in d.GetFileSystemlnfos()Folders.Enqueue(fi);)else(if(b)File.Create(f.FullName.Replace(parent,path);)18.复 制 文 件/using System.IO;File.Copy(%1,%2);19.复 制 个 文 件 夹 下 所 有 的 文 件 到 另 个 目 录/using System.IO;foreach(string fileStr in Directory.GetFiles(%1)File.Copy(%

21、1.Last I ndexOf(W)=%1.Length-1)?%1+Path.GetFileName(fileStr):%1+“+Path.GetFileName(fileStr),(%2.LastlndexOfC)=%2.Length-1)?%2+Path.GetFileName(fileStr):%2+Z+Path.GetFileNamedileStr):20.提 取 扩 展 名/using System.IO;string%2=Path.GetExtension(%1);21.提 取 文 件 名/using System.IO;string%2=Path.GetFileName(%1)

22、;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.10;File.Move(%1,%2+“+file.getname(%1);26.移 动 个 文 件 夹 下 所 有 文 件 到 另 个 目 录 foreach(string fileStr

23、in Directory.GetFiles(%1)FiIe.Move(%1.LastlndexOf(MV)=%1.Length-1)?%1+Path.GetFileName(fileStr):%1+“+Path.GetFileName(fileStr),(%2.LastlndexOf()=%2.Length-1)?%2+Path.GetFileName(fileStr):%2+Z+Path.GetFileNamedileStr):27.指 定 目 录 下 搜 索 文 件/*using System.Text;using System.IO;7string fileName=%1;string

24、dirName=%2;Directoryinfo dirc=new Directorylnfo(dirName);foreach(Filelnfo file in dirc.GetFiles()if(file.Name.lndexOf(fileName)-1)return file.FullName;)foreach(Directorylnfo dir in dirc.GetDirectories()return GetFile(fileName,dir.FullName);)return”找 不 到 指 定 的 文 件”;)28.打 开 对 话 框 OpenFileDialog penFil

25、eDialog=new OpenFileDialog();openFileDialog.lnitialDirectory=c:;注 意 这 里 写 路 径 时 要 用。而 不 是 c:OpenFileDialog.Filter=文 本 文 件|*.*|C#文 件|*.cs|所 有 文 件 OpenFileDialog.RestoreDirectory=true;OpenFileDialog.Filterlndex=1;if(OpenFileDialog.ShowDialog()=DialogResult.OK)fName=openFileDialog.FileName;File fileOpe

26、n=new File(fName);isFileHaveName=true;%1=fileOpen.ReadFile();%1.AppendTexttVV);)29.文 件 分 割/using System.IO;FileStream fsr=new FileStream(%1,FileMode.Open,FileAccess.Read);byte口 btArr=new bytefsr.Length;fsr.Read(btArr,0,btArr.Length);fsr.Close();string strFileName=%1.Substring(%1.LastlndexOf(V)+1);Fi

27、leStream fsw=new FileStream(%2+strFileName+1,FileMode.Create,FileAccess.Write);fsw.Write(btArr,0,btArr.Length/2);fsw.Close();fsw=new FileStream(%2+strFileName+2,FileMode.Create,FileAccess.Write);fsw.Write(btArr,btArr.Length/2,btArr.Length-btArr.Length/2);fsw.Close();30.文 件 合 并/using System.IO;string

28、 strFileName=%1.Substring(%1.LastlndexOf()+1);FileStream fsr1=new FileStream(%2+strFileName+1,FileMode.Open,FileAccess.Read);FileStream fsr2=new FileStream(%2+strFileName+2,FileMode.Open,FileAccess.Read);byte btArr=new bytefsr1.Length+fsr2.Length;fsr1.Read(btArr,0,Convert.Tolnt32(fsr1.Length);fsr2.R

29、ead(btArr,Convert.Tolnt32(fsr1.Length),Convert.Tolnt32(fsr2.Length);fsr1.CIose();fsr2.Close();FileStream fsw=new FileStream(%2+strFileName,FileMode.Create,FileAccess.Write);fsw.Write(btArr,0,btArr.Length);fsw.Close();31.文 件 简 单 加 密/using System.I0;读 文 件 FileStream fsr=new FileStream(%1,FileMode.Open

30、,FileAccess.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;btArri=Convert.ToByte(ibt);)写 文 件 string strFileName=Path.GetExtension(%1);FileStream fsw=new FileStream(%2+7+encj,+strFileName,FileMode.Creat

31、e,FileAccess.Write);fsw.Write(btArr,0,btArr.Length);fsw.Close();32.文 件 简 单 解 密/using System.IO;FileStream fsr=new FileStream(%1,FileMode.Open,FileAccess.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;i

32、bt%=256;btArri=Convert.ToByte(ibt);)写 文 件string strFileName=Path.GetExtension(%1);FileStream fsw=new FileStream(%2+7+strFileName,FileMode.Create,FileAccess.Write);fsw.Write(btArr,0,btArr.Length);fsw.Close();33.读 取 in i文 件 属 性/using System.Runtime.lnteropServices;/叩 川 0011”601932)/返 回 取 得 字 符 串 缓 冲 区

33、 的 长 度/private static extern long GetPrivateProfileString(string section,string key,string def,StringBuilderretVaIJnt size,string filePath);string Section=%1;string Key=%2;string NoText=%3;string iniFilePath=Setup.iniM;string%4=String.Empty;if(File.Exists(iniFilePath)StringBuilder temp=new StringBui

34、lder(1024);GetPrivateProfileString(Section,Key,NoText,temp,1024,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 fsr1=new FileStream(fileStr,FileMo

35、de.Open,FileAccess.Read);byte btArr=new bytefsr1.Length;fsr1.Read(btArr,0,Convert.Tolnt32(fsr1.Length);fsr1.Close();fsw.Write(btArr,0,btArr.Length);fsw.Close();35.写 入 in i文 件 属 性/using System.Runtime.InteropServices;/Dlllmport(”kemel32)返 回 0 表 示 失 败,非 0 为 成 功/private static extern long WritePrivateP

36、rofileStnng(string section,string key,string val,string filePath);string Section=%1;string Key=%2;string Value=%3;string iniFilePath=Setup.ini;bool%4=false;if(File.Exists(iniFilePath)(long pStation=WritePrivateProfileStringfSectioney,Value,iniFilePath);if(OpStation=0)%4=false;)else%4=true;)36.获 得 当

37、前 路 径 string%1=Environment.CurrentDirectory;37.读 取 XML数 据 库/using System.Xml;XmlDocument doc=new XmlDocument();doc.Load(%1);string%9;XmlElement xe=doc.GetElementByld(%7);XmlNodeList elemList=xe.ChildNodes;foreach(XmlNode elem in elemList)if(elem.NodeType=%8)%9=elem.Value;break;)38.写 入 XML数 据 库/using

38、 System.Xml;XmlDocument doc=new XmlDocument();doc.Load(%1);XmlNode root=doc.DocumentElement;XmlElement book=doc.CreateElement(%3);XmlElement book=doc.CreateElement(%5);XmlElement port=doc.CreateElement(%6);book.SetAttribute(%4,root.ChildNodes.Count.ToString();author.lnnerText=%8;book.appendChild(aut

39、hor);book.appendChild(port);root.appendChild(book);doc.Save(%1);39.ZIP压 缩 文 件/*using System.IO;using System.IO.Compression;7FileStream infile;try(/Open the file as a FileStream object.infile=new FileStream(%1,FileMode.Open,FileAccess.Read,FileShare.Read);byte buffer=new byteinfile.Length;/Read the f

40、ile to ensure it is readable.int count=infile.Read(buffer,0,buffer.Length);if(count!=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.DeflateStream compressedz

41、ipStream=new DeflateStream(ms,CompressionMode.Compress,true);/CompressioncompressedzipStream.Write(buffer,0,buffer.Length);/Close the pressedzipStream.Close();/Original size:0,Compressed size:,buffer.Length,ms.Length);Fileinfo f=new Filelnfo(%2);StreamWriter w=f.CreateText();w.Write(buffer,O,ms.Leng

42、th);w.Close();/end trycatch(InvalidDataException)/Error:The file being read contains 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

43、(PathTooLongException)/Error:The specified path,file name,or both exceed the system-defined maximum length.For example,on Windows-basedplatforms,paths must be less than 248 characters,and file names must be less than 260 characters.catch(DirectoryNotFoundException)“Error:The specified path is invali

44、d,such as being on an unmapped drive.catch(lOException)/Error:An I/O error occurred while opening the file.catch(UnauthorizedAccessException)“Error:path specified a file that is read-only,the path is a directory,or caller does not have the requiredpermissions.catch(IndexOutOfRangeException)/Error:Yo

45、u must provide parameters for MyGZIP.)40.ZIP解 压 缩/*using System.IO;using System.10.Compression;7FileStream infile;try/Open the file as a FileStream object.infile=new FileStream(%1,FileMode.Open,FileAccess.Read,FileShare.Read);byte buffer=new byteinfile.Length;/Read the file to ensure it is readable.

46、int count=infile.Read(buffer,0,buffer.Length);if(count!=buffer.Length)infile.Close();/Test Failed:Unable to read data from filereturn;infile.Close();MemoryStream ms=new MemoryStream();/ms.Position=0;DeflateStream zipStream=new DeflateStream(ms,CompressionMode.Decompress);/Decompressionbyte decompres

47、sedBuffer=new bytebuffer.Length*2;zipStream.Close();Fileinfo f=new Filelnfo(%2);Stream Writer w=f.CreateText();w.Write(decompressedBuffer);w.Close();/end trycatch(InvalidDataException)/Error:The file being read contains invalid data.)catch(FileNotFoundException)/Error:The file specified was not foun

48、d.)catch(ArgumentException)/Error:path is a zero-length string,contains only white space,or contains one or more invalidcharacterscatch(PathTooLongException)/Error:The specified path,file name,or both exceed the system-defined maximum length.Forexample,on Windows-basedplatforms,paths must be less th

49、an 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 error occurred while opening the file.)catch(UnauthorizedAccessException)/Error:path specified

50、 a file that is read-only,the path is a directory,or caller does not have therequiredpermissions.)catch(IndexOutOfRangeException)/Error:You must provide parameters for MyGZIP.)41.获 得 应 用 程 序 完 整 路 径 string%1=Application.Executable Path;42.ZIP压 缩 文 件 夹/*using System.IO;using System.lO.Compression;usi

展开阅读全文
相关资源
相关搜索

当前位置:首页 > 教育专区 > 教案示例

本站为文档C TO C交易模式,本站只提供存储空间、用户上传的文档直接被用户下载,本站只是中间服务平台,本站所有文档下载所得的收益归上传人(含作者)所有。本站仅对用户上传内容的表现方式做保护处理,对上载内容本身不做任何修改或编辑。若文档所含内容侵犯了您的版权或隐私,请立即通知得利文库网,我们立即给予删除!客服QQ:136780468 微信:18945177775 电话:18904686070

工信部备案号:黑ICP备15003705号-8 |  经营许可证:黑B2-20190332号 |   黑公网安备:91230400333293403D

© 2020-2023 www.deliwenku.com 得利文库. All Rights Reserved 黑龙江转换宝科技有限公司 

黑龙江省互联网违法和不良信息举报
举报电话:0468-3380021 邮箱:hgswwxb@163.com