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

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

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

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;
}
- 4 回答
- 0 關注
- 124 瀏覽
添加回答
舉報