首页 > 代码库 > C#读写txt文件

C#读写txt文件

读txt文件方法1:按行输出

1    public void Read(string path)
2    {
3         StreamReader sr = new StreamReader(path, Encoding.Default);
4         String line;
5         while ((line = sr.ReadLine()) != null)
6         {
7              Console.WriteLine(line.ToString());
8         }
9    }

读txt文件方法2:转换成char数组,然后输出(没有实际用过该方法)

 1   public void Read2(string path)
 2   { 
 3       byte[] byData = http://www.mamicode.com/new byte[100];
 4       char[] charData = http://www.mamicode.com/new char[1000];
 5       try
 6           {
 7               FileStream file = new FileStream(path, FileMode.Open);
 8               file.Seek(0, SeekOrigin.Begin);
 9               file.Read(byData, 0, 100); 
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    }

写txt文件方法1:只使用文件流

 1    public void Write()
 2    {
 3        FileStream fs = new FileStream("E:\\ak.txt", FileMode.Create);
 4        //获得字节数组
 5        byte[] data = http://www.mamicode.com/System.Text.Encoding.Default.GetBytes("Hello");
 6        byte[] data2 = System.Text.Encoding.Default.GetBytes("Hello World!");
 7        //开始写入
 8        fs.Write(data, 0, data.Length);
 9        fs.Write(data2, 0, data2.Length);
10        //清空缓冲区、关闭流
11        fs.Flush();
12        fs.Close();
13    }

写txt文件方法2:使用文件流和StreamWriter

 1    public void Write(string path)
 2    {
 3        FileStream fs = new FileStream(path, FileMode.Create);
 4        StreamWriter sw = new StreamWriter(fs);
 5        //开始写入
 6        sw.WriteLine("Hello");
 7        sw.WriteLine("Hello World!!!!");
 8        //清空缓冲区
 9        sw.Flush();
10        //关闭流
11        sw.Close();
12        fs.Close();
13    }

 

C#读写txt文件