添加命名空间

  System.IO;

  System.Text;

两种方法

使用StreamReader读取文件,然后一行一行的输出。

2.文件的读取

  (1).使用FileStream类进行文件的读取,并将它转换成char数组,然后输出。

c#txt文件读取

byte[] byData = new byte[100];

char[] charData = new char[1000];

public void Read()

{

try

{

FileStream file = new FileStream("E:\\test.txt", 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, charData, 0);

Console.WriteLine(charData);

file.Close();

}

catch (IOException e)

{

Console.WriteLine(e.ToString());

}

}

c#txt文件读取

  (2).使用StreamReader读取文件,然后一行一行的输出。

c#txt文件读取

public void Read(string path)

{

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

String line;

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

{

Console.WriteLine(line.ToString());

}

}


以上为网上资料

自己总结,两种方法

txt文件

c#txt文件读取

方法一:

对话框打开文件,使用StreamReader类ReadToEnd方法读取

private void button1_Click(object sender, EventArgs e)

        {

            try

            {

                openFileDialog1.Filter = "文本文件(*txt)|*.txt";

                openFileDialog1.ShowDialog();

                textBox1.Text = openFileDialog1.FileName;

                StreamReader sr = new StreamReader(textBox1.Text, Encoding.Default);

                //StreamReader sr = new StreamReader("d:\\text.txt", Encoding.Default);

                textBox2.Text = sr.ReadToEnd();

                //x = float.Parse(textBox2.Text);

                douX = double.Parse(textBox2.Text);

                //douX = (double)x;

                textBox3.Text = douX.ToString();

            }

            catch

            {

                MessageBox.Show("select file");

            }

        }

c#txt文件读取

 

方法二:

使用FileStream打开文件,使用StreamReader类读取数据,提取txt中两行数据存入变量。

  private void button2_Click(object sender, EventArgs e)

        {

            try

            {

                FileStream fs = File.OpenRead("d:\\test.txt");//打开文件

                StreamReader sr1 = new StreamReader("d:\\test.txt", Encoding.Default);

                string line;

                int lineNum;

                lineNum = 0;

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

                {  

                    lineNum ++;

                    if (lineNum == 1)

                    { textBox2.Text = line.ToString(); }

                    if (lineNum == 2)

                    { textBox3.Text = line.ToString(); }

                }

            }

            catch

            {

                MessageBox.Show("select file");

            }

        }

c#txt文件读取

c#txt文件读取

 

 

c#txt文件读取

 

 

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-07-29
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2021-09-21
  • 2021-08-04
  • 2022-12-23
  • 2021-07-24
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案