读取csv文件

1 string s = string.Empty;
2 string src = string.Empty;
3 SortedList sl = new SortedList();
4 StreamReader fs = new StreamReader(new FileStream("demo.csv", FileMode.Open, FileAccess.Read), Encoding.GetEncoding("gb2312"));
5 while (!string.IsNullOrEmpty(s = fs.ReadLine()))
6 {
7 if (!string.IsNullOrEmpty(s))
8 {
9 Console.WriteLine(s);
10 src = s.Replace("""", "'");
11 MatchCollection col = Regex.Matches(src, ","([^"]+)",", RegexOptions.ExplicitCapture);
12 IEnumerator ie = col.GetEnumerator();
13 while (ie.MoveNext())
14 {
15 string patn = ie.Current.ToString();
16 int key = src.Substring(0, src.IndexOf(patn)).Split(',').Length;
17 if (!sl.ContainsKey(key))
18 {
19 sl.Add(key, patn.Trim(new char[] { ',', '"' }).Replace("'", """));
20 src = src.Replace(patn, ",,");
21 }
22 }
23
24 string[] arr = src.Split(',');
25 for (int i = 0; i < arr.Length; i++)
26 {
27 if (!sl.ContainsKey(i))
28 sl.Add(i, arr[i]);
29 }
30
31 IDictionaryEnumerator ienum = sl.GetEnumerator();
32 while (ienum.MoveNext())
33 {
34 Console.WriteLine(string.Format("{0}:{1}", ienum.Key, ienum.Value.ToString().Replace("'", """)));
35 }
36 sl.Clear();
37 src = string.Empty;
38 }
39 Console.Read();
40 }
41 fs.Close();

你可能感兴趣的:(读取csv文件)