请教各位:我源代码如下,因为程序中有很多个按钮,每个按钮触发时开始都要读取该文件,想把读文件部分构造成一个函数,便于后面调用,要如何实现啊!请教啦!
 private void bottom1_Click(object sender, EventArgs e)      
{
            string path = "c:\\test1.text";
            FileStream fs = new FileStream(path, FileMode.OpenOrCreate);
                    StreamReader r = new StreamReader(fs );
                    while (r.Peek() != -1)
                    {
                        string s = r.ReadLine();  
                        if (s == "11")
                        text1.text = s;
                     }
              fs.Close();
              r.Close();
}

解决方案 »

  1.   

    如果是在同一个form里的话,直接在form里设置一个FileStream如果不在一个form里的话,就像1楼说的,直接写一个公共方法类,然后每个按钮里去调用
      

  2.   

    public string test(string _path)
    {
                string path = _path;
                string result;
                FileStream fs = new FileStream(path, FileMode.OpenOrCreate); 
                        StreamReader r = new StreamReader(fs ); 
                        while (r.Peek() != -1) 
                        { 
                            string s = r.ReadLine();  
                            if (s == "11") 
                            result = s; 
                        } 
                  fs.Close(); 
                  r.Close(); 
                  return result;
    }
    传一个路径参数,返回 文件内容
      

  3.   

    安装最近3年的vs(我猜你安装过,但是没有使用过),然后只要你用鼠标拖动选中多个代码行,点击鼠标右键,选择Refactor(重构)功能,就会弹出一个子菜单,其中就有将代码重构为一个函数的功能。非常方便。一旦你重构为函数,别的地方就调用它就可以了。
      

  4.   

    就是自己写个方法,不同的button来调用。
    sp1234给的vs的方法很快捷