Visual C#文件读取方式之一行方式

Visual C#读取文件方式有很多种,下面介绍第一种,行读取方式。

1.假设我们是通过一个按钮(openFile)促发一个文件选择对话框(openFileDialog),然后读取文件内容并显示到一个文本框(source)中,如果要演示,大家可以自己添加这两个控件。

2.下面我们就开始编写以行方式读取文件的方法,名字叫readFileByLine(),没有参数。

  private string readFileByLine() //这个方法将一行方式读取文件
        {    string fileText=string.Empty;
             OpenFileDialog openFileDialog = new OpenFileDialog(); //实例化一个打开文件对话框
           
               if (openFileDialog.ShowDialog()==true)  //如果文件打开成功
               {
                string fullPathname = openFileDialog.FileName;  //被打开文件全路径
                FileInfo src = new FileInfo(fullPathname);             
                TextReader reader = src.OpenText();              
                string lineStr = reader.ReadLine();
                    while (lineStr != null)  //未到文件结尾,逐行读取并赋值给返回字符串fileText
                {
                    fileText += lineStr + '\n';
                    lineStr = reader.ReadLine();
                }
                reader.Close();
                   }        

            return fileText;
        }

3.打开visual 2010在创建windows窗体应用程序或WPF应用程序,加入1所述的两个控件,并编写click事件,调用2.中方法,即可,代码及效果如下:

  private void openFileClick(object sender, RoutedEventArgs e)
        {
           source.Text= readFileByLine();
            
        }

 

Visual C#文件读取方式之一行方式

 


你可能感兴趣的:(C#,Visual,逐行读取文件,openFileDialog)