我正在创建一个小型 C# 程序,该程序从“用户选择的”位置读取纺织品。我已经成功地正确读取了文件,但如果用户输入以下内容,我想向他们显示一条错误消息文件名/路径不正确...或者文件类型不正确。 我已经在我有限的知识范围内尝试了一切,但现在我有点卡住了。任何帮助都将非常感激。谢谢
using System;
class ReadFromFile
{
static void Main()
{
Console.WriteLine ("Welcome to Decrypter (Press any key to begin)");
Console.ReadKey ();
//User selects file they wish to decrypt
int counter = 0;
string line;
string path;
Console.WriteLine ("\nPlease type the path to your file");
path = Console.ReadLine ();
// Read the file and display it line by line.
System.IO.StreamReader file =
new System.IO.StreamReader (path);
while ((line = file.ReadLine ()) != null) {
Console.WriteLine (line);
counter++;
}
file.Close ();
// Suspend the screen.
Console.ReadLine ();
}
}
最佳答案
使用
try
{
if (!File.Exists(path))
{
// Tell the user
}
}
catch (Exception ex)
{
// tell the user
}
检查文件是否存在
添加
using System.IO;
到代码文件顶部
关于c# - 检查用户是否输入了正确的文件系统路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33438046/