【问题标题】:Search for a file content in c#在c#中搜索文件内容
【发布时间】:2017-02-18 13:38:59
【问题描述】:

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

[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"); 获取文件的路径。

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

请告诉我该怎么做。

谢谢

【问题讨论】:

    标签: c# asp.net-mvc-5 asp.net-mvc-controller


    【解决方案1】:

    如果文件 usernameslist.txt 确实存在于根文件夹中名为 UserData 的子文件夹中,那么您只需将 Server.MapPath 的输出传递给 StreamReader构造函数

    string fileName = Server.MapPath("~/UserData/usernameslist.txt");
    
    using(StreamReader file = new System.IO.StreamReader(fileName))
    {
        ....
    }
    

    别忘了在 Stream 对象周围使用 using 语句

    【讨论】:

    • 非常感谢史蒂夫。 :)
    猜你喜欢
    • 2021-06-07
    • 1970-01-01
    • 2012-03-10
    • 1970-01-01
    • 1970-01-01
    • 2017-12-21
    • 1970-01-01
    • 2011-05-25
    • 1970-01-01
    相关资源
    最近更新 更多