【问题标题】:Validating (checking) a path entered exists验证(检查)输入的路径是否存在
【发布时间】:2012-01-06 00:45:04
【问题描述】:

我有一个程序,它有一个文件观察器,它的路径由用户输入(设置)。用户在文本框中输入路径,然后单击按钮设置文件观察器的路径

private void btnFileWatcherPath_Click(object sender, EventArgs e)
{
    fileWatcher.Path = txtFileWatcherPath.Text;
}

用另一个按钮打开文件观察器(程序中也有关闭按钮)

private void btnFileOn_Click(object sender, EventArgs e)
{
    fileWatcher.EnableRaisingEvents = true;
    btnFileOn.Visible = false;
    btnFileOff.Visible = true;
}

该程序有效,但我没有验证路径。输入的任何无效路径都会使程序崩溃。我怎样才能停止这种情况(希望标签显示“输入的路径无效”之类的内容)

【问题讨论】:

  • 不够清楚,抱歉是文件系统观察者。我正在查看整个目录而不仅仅是一个文件。只需将 File.Exist 更改为 Directory.Exist 并完成工作。干杯,感谢您的快速回复。

标签: c# validation path


【解决方案1】:

你可以使用File.Exists

private void btnFileWatcherPath_Click(object sender, EventArgs e)
{
    if(File.Exists(txtFileWatcherPath.Text)){
        fileWatcher.Path = txtFileWatcherPath.Text;
    }

}

【讨论】:

    【解决方案2】:

    您可以使用File.Exists

    if(File.Exists(path)){
        //Do some stuff
    }
    else{
        //It's bad man
    }
    

    【讨论】:

      【解决方案3】:

      我会在 try catch 块中执行,如果找不到路径则处理 io 异常

      http://msdn.microsoft.com/en-us/library/0yd65esw%28v=vs.80%29.aspx

      【讨论】:

        【解决方案4】:

        我认为您不想将文件监视器用于此目的。

        尝试使用 Directory.Exists(如果它是您正在检查的目录)

        http://msdn.microsoft.com/en-us/library/system.io.directory.exists.aspx

        【讨论】:

          【解决方案5】:

          通过以下任一方法验证路径是否存在:

          string path = txtFileWatcherPath.Text;
          

          这个(用于目录):

          System.IO.Directory.Exists(path);
          

          或者这个(对于实际文件):

          System.IO.File.Exists(path);
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2019-07-09
            • 2020-05-08
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2019-04-03
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多