C# 读写文件方法总结
using System.Collections.Generic;
using System.Text;
using System.IO;
char[] charData = new char[1000];
{
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();
//开始写入
fs.Write(data,0,data.Length);
fs.Flush();
fs.Close();
using System.Collections.Generic;
using System.Text;
using System.IO;
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 sw = new StreamWriter(fs);
//开始写入
sw.Write(String);
//清空缓冲区
sw.Flush();
//关闭流
sw.Close();
fs.Close();
-------------------------------------------------
一、写入文件
1.File类的静态方法WriteAllText(改写方式)
程序代码File.WriteAllText(Server.MapPath("a.txt"), "http://www.mzwu.com/\r\nhttp://www.hao123.com/\r\nhttp://www.163.com/");
2.File类的静态方法WriteAllLines(改写方式)
程序代码File.WriteAllLines(Server.MapPath("a.txt"), new string[] { "http://www.mzwu.com/", "http://www.hao123.com/", "http://www.163.com/" });
3.File类的静态方法AppendAllText(追加方式)
程序代码File.AppendAllText(Server.MapPath("a.txt"), "http://www.mzwu.com/\r\nhttp://www.hao123.com/\r\n");
File.AppendAllText(Server.MapPath("a.txt"), "http://www.163.com/");
4.StreamWriter对象的Write方法和WriteLine方法(true追加,false改写)
程序代码StreamWriter sw = new StreamWriter(Server.MapPath("a.txt"), false);
sw.Write("http://www.mzwu.com/\r\n");
sw.WriteLine("http://www.mzwu.com/");
sw.WriteLine("http://www.163.com/");
sw.Close();
说明:当文件不存在时,以上方法都将创建一个新文件!
二、读取文件
1.File类的静态方法ReadAllText
程序代码File.ReadAllText(Server.MapPath("a.txt"))
2.File类的静态方法ReadAllLines
程序代码string[] content = File.ReadAllLines(Server.MapPath("a.txt"));
for (int i = 0; i < content.Length; i++)
{
Response.Write(content[i] + "<br/>");
}
3.StreamReader对象的ReadToEnd方法
程序代码StreamReader sr = new StreamReader(Server.MapPath("a.txt"));
Response.Write(sr.ReadToEnd());
sr.Close();
4.StreamReader对象的ReadLine方法
程序代码StreamReader sr = new StreamReader(Server.MapPath("a.txt"));
while (!sr.EndOfStream)
{
Response.Write(sr.ReadLine() + "<br/>");
}
sr.Close();