转载请注明出处:http://www.cnblogs.com/ntotl/p/5152727.html

使用File:

1             if (File.Exists(importPath))
2             {
3                 string readText = File.ReadAllText(importPath);  //读取的结果包含了\r\n
4                 string[] lineList1 = File.ReadAllLines(importPath); 
5             }
View Code


使用StreamReader读:

 1 List<string> lineList2 = new List<string>(); 
 2 //ArrayList linesList2 = new ArrayList(); //
 3 
 4 StreamReader sr = new StreamReader(importPath);
 5 string oneline = sr.ReadLine();  //读当前一行
 6 
 7 while (!sr.EndOfStream)
 8 {
 9     lineList2.Add(sr.ReadLine());
10 }
11 sr.Close();
12 
13 if (lineList2.Count > 0)
14 {
15     for (int i = 0; i < lineList2.Count; i++)
16     {
17         string line = lineList2[i].ToString();
18         string regex = ",|,|\\s+";
19         string[] split = Regex.Split(line, regex);
20     }
21 }
View Code

这里提到了ArrayList 和 List<String>,记录一下,以便学习

http://zhidao.baidu.com/link?url=WwkEzOGYRxGeU0n0n4xsp5ROJDD6cKMwKhCRC_A7hwe6WnrATRwwye6aUQ0wJthEn0q3vRq704F53usl3OfH-a

 

使用FilsStream写:

1             string exportPath1 = "F:\\Upload\\ReadAndWriteFile\\streamreader1.txt";
2             FileStream fs1 = new FileStream(exportPath1, FileMode.OpenOrCreate);
3             byte[] data = new UTF8Encoding().GetBytes("aaaa");
4             fs1.Write(data, 0, data.Length);
5             fs1.Flush();
6             fs1.Close();
View Code

 

用StreamWriter写:

 1             #region 构造数据 dt
 2             DataTable dt = new DataTable();
 3             dt.Columns.Add("player");
 4             dt.Columns.Add("race");
 5             DataRow row = null;
 6             for (int i = 0; i < 5; i++)
 7             {
 8                 row = dt.NewRow();
 9                 row["player"] = "name_" + i;
10                 row["race"] = "race_" + i;
11                 dt.Rows.Add(row);
12             }
13             #endregion
14 
15             string exportPath2 = "F:\\Upload\\ReadAndWriteFile\\streamreader2.txt";
16             FileStream fs2 = new FileStream(exportPath2, FileMode.OpenOrCreate);
17             StreamWriter sw2 = new StreamWriter(fs2);
18             StringBuilder sb = new StringBuilder();
19             sb.Append("选手           种族\r\n");
20             foreach (DataRow dr in dt.Rows)
21             {
22                 sb.Append(dr["player"] + "           " + dr["race"] + "\r\n");
23             }
24             sw2.Write(sb);
25             sw2.Flush();
26             sw2.Close();
27             fs2.Close();
View Code

 

由于本人刚毕业不久,目前主要从事ASP.NET方面的开发,所以上面的代码读取之后还处理了,是方便写入数据库,导出也是如此,可用于把数据备份到txt文件。

本人还处于学习阶段,如有理解或者代码错误,还请不吝赐教。

posted on 2016-01-23 01:10  雪落千寒  阅读(6463)  评论(1编辑  收藏  举报