c#txt文件的读写

王朝学院·作者佚名  2016-08-27
窄屏简体版  字體: 小  |  中  |  大  |  超大  

namespace file

{

class MyFile

{

string FilePath;

byte[] byData = new byte[100];

public char[] MyData = new char[1000];

public string reslutstr = null;

public MyFile()

{ }

public MyFile(string path)

{

FilePath = path;

}

public void ReadFile1()

{

try

{

FileStream file = new FileStream(FilePath, FileMode.Open);

file.Seek(0, SeekOrigin.Begin);

file.Read(byData, 0, 100); //byData传进来的字节数组,用以接受FileStream对象中的数据,第2个参数是字节数组中开始写入数据的位置,它通常是0,表示从数组的开端文件中向数组写数据,最后一个参数规定从文件读多少字符.

Decoder d = Encoding.Default.GetDecoder();

d.GetChars(byData, 0, byData.Length, MyData, 0);

//Console.WriteLine(MyData);

foreach (char ch in MyData)

{

reslutstr += ch.ToString();

}

file.Close();

}

catch (IOException e)

{

Console.WriteLine(e.ToString());

}

}

public void ReadFile2()

{

StreamReader sr = new StreamReader(FilePath, Encoding.Default);

String line;

while ((line = sr.ReadLine()) != null)

{

reslutstr += line;

// Console.WriteLine(line.ToString());

}

}

public void SaveFile1(string savestr)

{

FileStream fs = new FileStream(FilePath, FileMode.Create);

//获得字节数组

byte[] data = System.Text.Encoding.Default.GetBytes(savestr);

//开始写入

fs.Write(data, 0, data.Length);

//清空缓冲区、关闭流

fs.Flush();

fs.Close();

}

public void SaveFile2()

{

FileStream fs = new FileStream(FilePath, FileMode.Create);

StreamWriter sw = new StreamWriter(fs);

//开始写入

sw.Write("Hello World!!!!");

//清空缓冲区

sw.Flush();

//关闭流

sw.Close();

fs.Close();

}

}

}

//调用方法:

MyFile MyFile = new MyFile(Filepath);

string result = null;

// MyFile.SaveFile1(savastr);

MyFile.SaveFile2();

MyFile.ReadFile2();

 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
© 2005- 王朝網路 版權所有 導航