static public SqlConnection conn
       {
           get
           {
               StreamReader file = new StreamReader("d:\\sqlcnf.txt");
               string source = file.ReadToEnd();
               return new SqlConnection(source);
           }
       }
       static void Main(string[] args)
        {
            conn.Open();
            SqlCommand cmd = new SqlCommand("select * from [MyJob]", conn);
            SqlDataReader reader = cmd.ExecuteReader();
       ...
然后就会出错
Unhandled Exception: System.InvalidOperationException: ExecuteReader requir open and available Connection. The connection's current state is closed.  
如果我返回一个连接字符,串然后建立连接就没问题,这是为什么

解决方案 »

  1.   

    如果调用方法失败不是由无效参数造成的,则使用 InvalidOperationException。例如,对于 InvalidOperationException 而言: 如果创建枚举数后修改了集合中的对象,则由 MoveNext 引发该异常。如果执行方法调用前关闭了资源集,则由 GetString 引发该异常。如果方法调用失败是由无效参数造成的,则应改为引发 ArgumentException 或其派生类 ArgumentNullException 或 ArgumentOutOfRangeException。LdfldaMicrosoft 中间语言 (MSIL) 指令引发 InvalidOperationException。InvalidOperationException 使用值为 0x80131509 的 HRESULT COR_E_INVALIDOPERATION。
      

  2.   

     可能是没有写datareader.Read()
      

  3.   

    因为先执行conn.Open();,new了一个SqlConnection,并打开连接;然后SqlCommand构造方法执行时又new了一个新的SqlConnection,此SqlConnection的连接并没有打开。所以报错。
      

  4.   

    连接字符串放到配置文件中去,不要自己弄个txt,这样反而不安全
    即使你要用
    也应该是定义一个全局的static readonly string source = new StreamReader("d:\\sqlcnf.txt").ReadToEnd(); SqlDataReader reader = cmd.ExecuteReader();
    if(reader.HasRows)
    {
       while(reader.Read())
          //....
    }
      

  5.   

    如果要像楼主那么写,可以将conn.Open();这句移入conn属性get定义中,打开连接后再return。