服务热线:13616026886

技术文档 欢迎使用技术文档,我们为你提供从新手到专业开发者的所有资源,你也可以通过它日益精进

位置:首页 > 技术文档 > JAVA > 新手入门 > 基础入门 > 查看文档

c#编程实用技巧:轻松实现对文件的操作

和java一样,c#提供的类库能够轻松实现对文件的操作。下面就给出代码示例,大家可以参考一下。

  //c#写入/读出文本文件 
  string filename =@"c:i.txt"; 
  streamreader sr = new streamreader(filename); string str=sr.readline (); sr.close();
  streamwriterrw=file.createtext(server.mappath(".")+"/mytext.txt"); 
  rw.writeline("写入"); 
  rw.writeline("abc"); 
  rw.writeline(".net笔记"); 
  rw.flush(); 
  rw.close(); 
  //打开文本文件 
  streamreadersr=file.opentext(server.mappath(".")+"/mytext.txt"); 
  stringbuilderoutput=newstringbuilder(); 
  stringrl; 
  while((rl=sr.readline())!=null) 
  ...{ 
  output.append(rl+""); 
  } 
  lblfile.text=output.tostring(); 
  sr.close(); 
  //c#追加文件 
  streamwritersw=file.appendtext(server.mappath(".")+"/mytext.txt"); 
  sw.writeline("追逐理想"); 
  sw.writeline("kzlll"); 
  sw.writeline(".net笔记"); 
  sw.flush(); 
  sw.close(); 
  //c#拷贝文件 
  stringorignfile,newfile; 
  orignfile=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; 
  orignfile=server.mappath(".")+"/mytext.txt"; 
  newfile=server.mappath(".")+"/mytextcopy.txt"; 
  file.move(orignfile,newfile); 
  //c#创建目录 
  //创建目录c:sixage 
  directoryinfod=directory.createdirectory("c:/sixage"); 
  //d1指向c:sixagesixage1 
  directoryinfod1=d.createsubdirectory("sixage1"); 
  //d2指向c:sixagesixage1sixage1_1 
  directoryinfod2=d1.createsubdirectory("sixage1_1"); 
  //将当前目录设为c:sixage 
  directory.setcurrentdirectory("c:/sixage"); 
  //创建目录c:sixagesixage2 
  directory.createdirectory("sixage2"); 
  //创建目录c:sixagesixage2sixage2_1 
  directory.createdirectory("sixage2/sixage2_1");

但是,在对txt文件读的操作中貌似没问题。因为代码能实现文件的读操作,但是所读txt文件包含中文的时候就以乱码显示。查了半天资料,看似复杂的问题其实很简单就能解决,稍微改动一下即可:

streamreader sr = new streamreader(filename,encoding.getencoding("gb2312"));

扫描关注微信公众号