亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

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

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

C#
瀟湘沐 2022-08-20 15:55:12
我創建了一個帶有字符串參數的布爾方法。雖然值為 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。
查看完整描述

4 回答

?
湖上湖

TA貢獻2003條經驗 獲得超2個贊

您首先讀取該文件,然后檢查它是否存在。當然,你必須使用另一種方式:


public static bool init_access(string file_path)

{

    if (!File.Exists(file_path))

    {

        return false;

    }


    int counter = 0;

    string[] lines = File.ReadAllLines(file_path);

    foreach (string line in lines)    

    {   

        counter++;

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

    }


    return true;

}


查看完整回答
反對 回復 2022-08-20
?
富國滬深

TA貢獻1790條經驗 獲得超9個贊

一般來說(或偏執的)案例文件可以在檢查后出現/取消(創建或刪除)。捕獲異常 () 是肯定的,但速度較慢:File.ExistsFileNotFoundException


public static bool init_access(string file_path)

{

    try 

    {

        foreach (string item in File

              .ReadLines(file_path)

              .Select((line, index) => $"{index + 1} {line}"))

            Console.WriteLine(item);


        return true;

    }

    catch (FileNotFoundException) 

    {

        return false;

    }

}


查看完整回答
反對 回復 2022-08-20
?
撒科打諢

TA貢獻1934條經驗 獲得超2個贊

試試這個:


    public static bool init_access(string file_path)

    {

        if (File.Exists(file_path))

        {

            int counter = 0;

            foreach (string line in File.ReadAllLines(file_path))

            {

                counter++;

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

            }


            return true;

        }


        return false;

    }


查看完整回答
反對 回復 2022-08-20
?
慕田峪9158850

TA貢獻1794條經驗 獲得超8個贊

正如Rango所說,是的,您必須首先檢查該文件是否存在。如果您喜歡較小的解決方案:


public static bool init_access(string file_path)

{

    if (File.Exists(file_path))

    {

        var counter = 0;

        File.ReadAllLines(file_path).ToList().ForEach(x => Console.WriteLine(counter++ + " " + x));


        return true;

    }


    return false;

}


查看完整回答
反對 回復 2022-08-20
  • 4 回答
  • 0 關注
  • 124 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號