在公司实习,任务不太重,总结一下c#关于txt文件的读写,以便以后有用到的时候可以查看一下。如果有写得不完整的地方还请补充

说明:本人C#水平可能初级都谈不上,高手轻喷,参考:http://www.cnblogs.com/akwwl/p/3240813.html

其他的都不说了,直接将完整的类放上:

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

我是使用form中的label进行显示的,其他的都没有弄,只是作为读和写。