c# - 检查用户是否输入了正确的文件系统路径

标签 c#

我正在创建一个小型 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/

相关文章:

c# - WPF到跨平台开发,最强的跨平台UI框架是什么?

c# - 我可以在 C# 中创建这种类型的事件吗?

c# - 影响 Streamsource 从一个位图到另一个位图不起作用

c# - 如何设置 SQL Server 表中的最大行数?

c# - Entity Framework 单个漂亮的错误消息

c# - 通过代码隐藏中的数据表分页

c# - 检索 SQL Server 中表的 DataTable 信息

c# - 在 C# 中将列表组合转换为逗号分隔的字符串

c# - 最适合模型的位图类

c# - 选择具有组最小值的组的所有元素