C# 指定字符串截取方法

在网上找一些资料,自己整理的一个方法.自己感觉还不错,想与大家分享.若此方法还有不足,还请大家多指教.谢谢..     

 1         /// <summary>
 2         /// 在文件数据流中以行读取需要的指定的字符串截取.
 3         /// </summary>
 4         /// <param name="strFilePath">文件路径绝对路径</param>
 5         /// <param name="strBeginKey">找到开始截取的字符串</param>
 6         /// <param name="strEndkey">找到结束的字符串</param>
 7         /// <returns></returns>
 8         public string GetSelectKey(string strFilePath, string strBeginKey, string strEndkey) 
 9         {
10             string input = "";//输入的字符串
11             string strTitle = "";
12             int a;//索引值(位置) 标记
13             int b;//索引值(位置) 标记
14             bool goon = true;//标记
15 
16             #region 获得文件标题
17             using (StreamReader sr = new StreamReader(strFilePath, Encoding.GetEncoding("gb2312")))
18             {
19                 while ((input = sr.ReadLine()) != null && goon)//行读取
20                 {
21                     a = input.IndexOf(strBeginKey);//"查找“字串”的开始字符在input中的索引值(位置) 
22                     if (a >= 0)
23                     {
24                         b = input.IndexOf(strEndkey);//"查找“字串”的结束字符在input中的索引值(位置) 
25                         if (b - a - strBeginKey.Length == 0)
26                         {
27                             strTitle = "无标题";
28                         }
29                         else
30                         {
31                             //截取字符串
32                             strTitle = input.Substring(a + strBeginKey.Length, b - a - strBeginKey.Length);
33                             goon = false;//标记变量
34                         }
35                     }
36                 }
37             }
38             #endregion
39 
40             return strTitle;
41         }

我在项目中是读取项目中所有的"*.aspx"文件中标题"<title>...</titie> ".
方法的调用:

  

1                     //绝对路径
2                     string strFilePath = NextFile.DirectoryName + "/" + NextFile.Name;
3                     string strBeginKey = "<title>";
4                     string strEndkey = "</title>";
5                     dr["Title"] = GetSelectKey(strFilePath, strBeginKey, strEndkey);//标题


这样就可以取到:"<title>...</title>"中的标题.


 

 

 

posted @ 2013-10-20 15:09  KenyonLi  阅读(2211)  评论(0编辑  收藏  举报