2017-02-18 103 views
1

嗨我写了一个C#代码,其中有一个字符串作为参数输入发送到方法。然后必须在文件中搜索inputString,并返回结果。目前我知道我如何以常规方式(使用文件IO)执行此操作。在c#中搜索文件内容#

[HttpPost] 
     public string UsernameValidation(string username) 
     { 
      string text = username; 
      string userExists = usernameNotAvailable; 
      string line; 
      System.IO.StreamReader file = new System.IO.StreamReader("~/UserData/usernameslist.txt"); 

      while ((line = file.ReadLine()) != null) 
      { 
       if (line.Contains(text)) 
       { 
        userExists = usernameAvailable; 
       } 

      } 
      return userExists; 
     } 

但是,这里是扭曲的,我的项目是在MVC。我可以使用string userDataFile = Server.MapPath("~/UserData/usernameslist.txt");来获取文件的路径。

但我无法知道如何获得在文件中搜索字符串的功能。

请让我知道我该怎么做。

感谢

回答

1

如果文件usernameslist.txt一个从你的根文件夹命名为的UserData子文件夹内确实存在,那么你只需要使用Server.Mappath的输出传递到您的StreamReader构造

string fileName = Server.MapPath("~/UserData/usernameslist.txt"); 

using(StreamReader file = new System.IO.StreamReader(fileName)) 
{ 
    .... 
} 

而且不要忘记使用using语句围绕Stream对象

+0

谢谢你太多史蒂夫了。 :) – user3872094