开发者

read a text file word by word and put this word in a list with c#

开发者 https://www.devze.com 2023-03-28 12:56 出处:网络
i work a project with asp.net mvc2 (c#) and i want to show the content of my text file in my page .ascx in bold any keyword.I think I prove it with one model that contains alist of word from my text f

i work a project with asp.net mvc2 (c#) and i want to show the content of my text file in my page .ascx in bold any keyword.I think I prove it with one model that contains a list of word from my text file and in my page I display word by word if I find the keyword I change the police. how can I read a text file word by word and开发者_如何学编程 put the word in a list with C #


I suppose you have a list of keywords that may be exist in your text file, so what you really need is just read all text as one string then loop over keywords list and replace the matching with the same keyword but surrounded by <b> tag some thing like that

To put your keywords into list of String

List<String> KeywordsList = new List<String>();
//replace keyWord_1,keyWord_2,keyWord_3, and keyWord_4 by your keywords
KeywordsList.Add("keyWord_1");
KeywordsList.Add("keyWord_2");
KeywordsList.Add("keyWord_3");
KeywordsList.Add("keyWord_4");

or you can store it in a Database then read it instead of hardcoded list.

To Read Text file

public String GetBoldedText()
{
   String allText = File.ReadAllText("FilePath"); // ex. C:\\MyFolder\\MyText.txt
   foreach(String keyword in KeywordsList)
   {
      alltext = alltext.Replace(keyword,"<b>"+keyword+"</b>");
   }
   return alltext;
}

you should add using System.IO; to using block of your class to use File class

0

精彩评论

暂无评论...
验证码 换一张
取 消