asp教程.net c#读写文件应用实例与详解
1、使用filestream读写文件
文件头:
using system;
using system.collections.generic;
using system.text;
using system.io;
读文件核心代码:
byte[] bydata = new byte[100];
char[] chardata = new char[1000];
try
{
filestream sfile = new filestream("文件路径",filemode.open);
sfile.seek(55, seekorigin.begin);
sfile.read(bydata, 0, 100); //第一个参数是被传进来的字节数组,用以接受filestream对象中的数据,第2个参数是字节数组中开始写入数据的位置,它通常是0,表示从数组的开端文件中向数组写数据,最后一个参数规定从文件读多少字符.
}
catch (ioexception e)
{
console.writeline("an io exception has been thrown!");
console.writeline(e.tostring());
console.readline();
return;
}
decoder d = encoding.utf8.getdecoder();
d.getchars(bydata, 0, bydata.length, chardata, 0);
console.writeline(chardata);
console.readline();
写文件核心代码:
filestream fs = new filestream(文件路径,filemode.create);
//获得字节数组
byte [] data =new utf8encoding().getbytes(string);
//开始写入
fs.write(data,0,data.length);
//清空缓冲区、关闭流
fs.flush();
fs.close();
2、使用streamreader和streamwriter
文件头:
using system;
using system.collections.generic;
using system.text;
using system.io;
streamreader读取文件:
streamreader objreader = new streamreader(文件路径);
string sline="";
arraylist linelist = new arraylist();
while (sline != null)
{
sline = objreader.readline();
if (sline != null&&!sline.equals(""))
linelist.add(sline);
}
objreader.close();
return linelist;
streamwriter写文件:
filestream fs = new filestream(文件路径, filemode.create);
streamwriter sw = new streamwriter(fs);
//开始写入
sw.write(string);
//清空缓冲区
sw.flush();
//关闭流
sw.close();
fs.close();