如何在 Main Method中返回具有字符串参数的 bool 方法

我创建了一个带有字符串参数的布尔方法。虽然值为 true,但它有效,但在 false 上,它给出一个错误。在 main 方法中调用 bool 方法时,它不接受来自 bool 方法的相同字符串参数。


public static bool init_access(string file_path)

{


    int counter = 0;

    file_path = @"C:\Users\waqas\Desktop\TextFile.txt";

    List<string> lines = File.ReadAllLines(file_path).ToList();

    foreach (string line in lines)


    {


        counter++;

        Console.WriteLine(counter + " " + line);

    }

    if (File.Exists(file_path))

    {


        return (true);


    }


    return false;

}

如果文件确实存在,它应该返回 true,否则它应该返回 false。


潇湘沐
浏览 206回答 4
4回答

湖上湖

您首先读取该文件,然后检查它是否存在。当然,你必须使用另一种方式:public static bool init_access(string file_path){&nbsp; &nbsp; if (!File.Exists(file_path))&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; return false;&nbsp; &nbsp; }&nbsp; &nbsp; int counter = 0;&nbsp; &nbsp; string[] lines = File.ReadAllLines(file_path);&nbsp; &nbsp; foreach (string line in lines)&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; {&nbsp; &nbsp;&nbsp; &nbsp; &nbsp; &nbsp; counter++;&nbsp; &nbsp; &nbsp; &nbsp; Console.WriteLine(counter + " " + line);&nbsp; &nbsp; }&nbsp; &nbsp; return true;}

富国沪深

一般来说(或偏执的)案例文件可以在检查后出现/取消(创建或删除)。捕获异常 () 是肯定的,但速度较慢:File.ExistsFileNotFoundExceptionpublic static bool init_access(string file_path){&nbsp; &nbsp; try&nbsp;&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; foreach (string item in File&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .ReadLines(file_path)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .Select((line, index) => $"{index + 1} {line}"))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Console.WriteLine(item);&nbsp; &nbsp; &nbsp; &nbsp; return true;&nbsp; &nbsp; }&nbsp; &nbsp; catch (FileNotFoundException)&nbsp;&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; return false;&nbsp; &nbsp; }}

撒科打诨

试试这个:&nbsp; &nbsp; public static bool init_access(string file_path)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; if (File.Exists(file_path))&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; int counter = 0;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; foreach (string line in File.ReadAllLines(file_path))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; counter++;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Console.WriteLine(counter + " " + line);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return true;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; return false;&nbsp; &nbsp; }

慕田峪9158850

正如Rango所说,是的,您必须首先检查该文件是否存在。如果您喜欢较小的解决方案:public static bool init_access(string file_path){&nbsp; &nbsp; if (File.Exists(file_path))&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; var counter = 0;&nbsp; &nbsp; &nbsp; &nbsp; File.ReadAllLines(file_path).ToList().ForEach(x => Console.WriteLine(counter++ + " " + x));&nbsp; &nbsp; &nbsp; &nbsp; return true;&nbsp; &nbsp; }&nbsp; &nbsp; return false;}
打开App,查看更多内容
随时随地看视频慕课网APP