Posted on 2009-07-07 15:53
Hero 阅读(222)
评论(0) 编辑 收藏 引用 所属分类:
C#积累
1 using System;
2 using System.Collections.Generic;
3 using System.Text;
4
5 using System.IO;
6
7 namespace Stream2
8 {
9 class Program
10 {
11 private static List<Dictionary<string, string>>
12 GetData( out List<string>columns )
13 {
14 string strline;
15 string[] strArry;
16 char[] charArry = new char[] { ',' } ;//分割字符
17 List<Dictionary<string, string>> data = new List<Dictionary<string, string>>();
18
19 columns = new List<string>();
20
21 try
22 {
23 //创建文件流
24 FileStream filestream = new FileStream( "Log.txt", FileMode.OpenOrCreate ) ;
25 StreamReader reader = new StreamReader( filestream );
26
27 //obtain the columns from the first line
28 //split row of data into string array
29
30 strline = reader.ReadLine();//读入第一行
31 strArry = strline.Split( charArry );//获得“,”分割的列名称
32
33 for( int i=0; i<=strArry.GetUpperBound(0); i++ )
34 {
35 columns.Add( strArry[i] );
36 }
37
38 strline = reader.ReadLine();
39 while( strline != null )
40 {
41 strArry = strline.Split( charArry );
42
43 Dictionary<string, string> dataRow = new Dictionary<string, string>();
44
45 for( int i=0; i<=strArry.GetUpperBound(0); i++ )
46 {
47 dataRow.Add( columns[i], strArry[i] );
48 }
49
50 data.Add( dataRow );
51
52 strline = reader.ReadLine();
53 }
54
55 reader.Close();
56
57 return data;
58 }
59 catch ( IOException ex )
60 {
61 Console.WriteLine( ex.ToString() );
62 return data;
63 }
64
65 return data;
66 }
67
68
69 static void Main( string[] args )
70 {
71 List<string> columns;
72 List<Dictionary<string, string>> myData = GetData( out columns );
73
74 foreach ( string column in columns )
75 {
76 Console.Write( "{0,-20}", column );
77 }
78 Console.WriteLine();
79
80 foreach ( Dictionary<string, string> row in myData )
81 {
82 foreach ( string column in columns )
83 {
84 Console.Write( "{0,-20}", row[column] );
85 }
86 Console.WriteLine();
87 }
88 }
89 }
90 }
91