需要统计一个串或一个文本中的文本行数 利用正则表达式来匹配换行符,实现统计 public static long LineCount(string source, bool isFileName) { if (source != null) { string text = source; if (isFileName) { using (FileStream fs = new FileStream(source, FileMode.Open, FileAccess.Read, FileShare.Read)) using (StreamReader sr = new StreamReader(fs)) { text = sr.ReadToEnd(); } } Regex Re = new Regex("/n", RegexOptions.Multiline); MatchCollection theMatches = Re.Matches(text); if (isFileName) { return (theMatches.Count); } else return theMatches.Count + 1; } else return (0); } public static long LineCount2(string source, bool isFileName) { if (source != null) { string text = source; long numCount = 0; if (isFileName) { using (FileStream fs = new FileStream(source, FileMode.Open, FileAccess.Read, FileShare.Read)) using (StreamReader sr = new StreamReader(fs)) { while (text != null) { text = sr.ReadLine(); if (text != null) { numCount++; } } } return numCount; } else { Regex Re = new Regex("", RegexOptions.Multiline); MatchCollection theMatch = Re.Matches(text); return theMatch.Count + 1; } } else { return (0); } }