WebService序列化DataTable

    [WebMethod]
    public DataTable Show( string filename)
    {
        XmlSerializer ser = new XmlSerializer( typeof( DataTable ) );
        DataTable table = new DataTable( "User" );
        DataColumn col = new DataColumn( "string" );

        table.Columns.Add( col );
        DataRow r;

        for ( int i = 0; i < 10; i++ )
        {
            r = table.NewRow( );
            r[ 0 ] = "元" + i;
            table.Rows.Add( r );
        }

        TextWriter writer = new StreamWriter( filename );
        ser.Serialize( writer, table );
        return table;
    }

    [WebMethod]
    public DataTable ShowUSer( string connectionString )
    {
        DataTable dt = new DataTable( "User" );
        XmlSerializer ser = new XmlSerializer( typeof( DataTable ) );

        connectionString = "Data Source=1c8a2f252c6e43e;database=cnblogs;uid=sa;pwd=sa";
        string sqlstr = @"SELECT  [userId]
      ,[userName]
      ,[password]
      ,[displayName]
      ,[Email]
      ,[gender]
  FROM [cnblogs].[dbo].[User]";

        using ( SqlConnection conn = new SqlConnection( connectionString ) )
        {
          
            conn.Open( );
            Console.WriteLine( "连接成功" );
            SqlCommand comm = new SqlCommand( sqlstr, conn );
            SqlDataReader reader = comm.ExecuteReader( );

            DataTable schema = reader.GetSchemaTable( );

            foreach ( DataRow r in schema.Rows )
            {
                DataColumn col = new DataColumn(
                    r[ "columnName" ] as string,
                    r[ "DataType" ] as Type
                    );
                dt.Columns.Add( col );
                //dt.Rows.Add( col );
            }

            while ( reader.Read( ) )
            {
                DataRow row = dt.NewRow( );
                for ( int i = 0; i < dt.Columns.Count; i++ )
                {
                    row[ i ] = reader[ i ];
                    Console.Write( "", dt.Columns.ToString( ) );
                }
                dt.Rows.Add( row );
            }

            reader.Close( );
            dt.AcceptChanges( );


        }

        foreach ( DataRow r in dt.Rows )
        {
          
            for ( int i = 0; i < dt.Columns.Count; i++ )
            {
                Console.Write( "{0}\t", r[ i ] );
            }
            Console.WriteLine( );
        }

        TextWriter writer = new StreamWriter( connectionString );
        ser.Serialize( writer, dt );
        return dt;
    }

posted @ 2012-07-01 13:04  blog_yuan  阅读(2117)  评论(0编辑  收藏  举报