简体   繁体   English

想检查 IF File.Exists 来定义 StreamReader,然后搜索特定的行

[英]Want to check IF File.Exists to define StreamReader, to then searching for specific line

I don't write code often and my knowledge is still low-level.我不经常写代码,我的知识仍然很低级。 I need help for something that I can't figure out我需要帮助解决我无法弄清楚的事情

    public static void SearchScriptEnd()
    {
        int counter = 0;
        string line;
        Report.Log(ReportLevel.Info, "Read Log", "Starting to find: Test Suite Ended");
        var text = "Test Suite Ended";
        
        if (File.Exists(ConfigController.Home + TestSuite.Current.Parameters["LogPath"]))
        {
            StreamReader file = 
                new StreamReader(ConfigController.Home + TestSuite.Current.Parameters["LogPath"]);
        }else{
            
            StreamReader file = 
                new StreamReader(TestSuite.Current.Parameters["LogPath"]);
        }
        
        while ((line = file.ReadLine()) != null)
        {
            if (line.Contains(text))
            {
                Report.Log(ReportLevel.Info, "Read Log", "[Success] Script End String has been found");
                Report.Log(ReportLevel.Info, "Read Log", string.Format("Line number: '{0}'", counter));
                return;
            }
       
            counter++;
        }
        
        Report.Log(ReportLevel.Failure, "Read Log", "[Missing] Anvil Script End String NOT found");
        file.Close();
    }

At first, the while was in both statement and was working well, but I want to use the While outside of that statement, but I'm getting The name 'file' does not exist in the current context (CS0103) and I don't know how to get the value of file out of my If statement.起初,while 在这两个语句中并且运行良好,但我想在该语句之外使用 While,但我得到 The name 'file' does not exist in the current context (CS0103) and I don't不知道如何从我的 If 语句中获取文件的值。

You need to get the variable out of the if-scope.您需要将变量移出 if 范围。 Try this:尝试这个:

    StreamReader file;
    if (File.Exists(ConfigController.Home + TestSuite.Current.Parameters["LogPath"]))
    {
        file = new StreamReader(ConfigController.Home + TestSuite.Current.Parameters["LogPath"]);
    }else{            
        file = new StreamReader(TestSuite.Current.Parameters["LogPath"]);
    }

That way you have a value in file for sure.这样你肯定在文件中有一个价值。 Happy coding.快乐编码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM