C#文件的读写

通过FileStream类进行文件的读写

1.读文件

  

 1 byte[] byData = new byte[100];
 2         char[] charData = new char[1000];
 3         public void Read()
 4         {
 5             try
 6             {
 7                 FileStream file = new FileStream("E:\\test.txt", FileMode.Open);
 8                 file.Seek(0, SeekOrigin.Begin);
 9                 file.Read(byData, 0, 100); //byData传进来的字节数组,用以接受FileStream对象中的数据,第2个参数是字节数组中开始写入数据的位置,它通常是0,表示从数组的开端文件中向数组写数据,最后一个参数规定从文件读多少字符.
10                 Decoder d = Encoding.Default.GetDecoder();
11                 d.GetChars(byData, 0, byData.Length, charData, 0);
12                 Console.WriteLine(charData);
13                 file.Close();
14             }
15             catch (IOException e)
16             {
17                 Console.WriteLine(e.ToString());
18             }
19         }

2.写文件

  

public void Write()
        {
            FileStream fs = new FileStream("E:\\ak.txt", FileMode.Create);
            //获得字节数组
            byte[] data = System.Text.Encoding.Default.GetBytes("Hello World!"); 
            //开始写入
            fs.Write(data, 0, data.Length);
            //清空缓冲区、关闭流
            fs.Flush();
            fs.Close();
        }

 

 

通过StreamReader StreamWriter读写文件

1.读文件

  

public void Read(string path)
        {
            StreamReader sr = new StreamReader(path,Encoding.Default);
            String line;
            while ((line = sr.ReadLine()) != null) 
            {
                Console.WriteLine(line.ToString());
            }
        }

 

2.写文件

public void Write(string path)
        {
            FileStream fs = new FileStream(path, FileMode.Create);
            StreamWriter sw = new StreamWriter(fs);
            //开始写入
            sw.Write("Hello World!!!!");
            //清空缓冲区
            sw.Flush();
            //关闭流
            sw.Close();
            fs.Close();
        }

 

posted @ 2017-06-24 21:16  ZOL  阅读(161)  评论(0)    收藏  举报
// 侧边栏目录