要检查 IF File.Exists 以定义 StreamReader,然后搜索特定行

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

我不经常写代码,我的知识水平还很低。我需要一些我无法弄清楚的帮助

    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();
    }

起初,while 在两个语句中都存在并且运行良好,但我想在该语句之外使用 While,但我得到 The name 'file' does not exist in the current context (CS0103) 我不知道如何从我的 If 语句中获取文件的值。

您需要将变量移出 if 范围。试试这个:

    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"]);
    }

这样你肯定在文件中有一个值。编码愉快。