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条经验 获得超7个赞
正如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 关注
- 99 浏览
添加回答
举报