c# txt文件的读写

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();

c# txt文件的读写

上一篇:SQL复习


下一篇:mysql--返回一个数字n,使得 a<=n<=b