【问题标题】:How can I check if the path entered by user is valid or not? [duplicate]如何检查用户输入的路径是否有效? [复制]
【发布时间】:2014-12-19 06:39:01
【问题描述】:

我在忙于寻找答案时发现了这段代码!

private void btnOpenFile_Click(object sender, EventArgs e)
{
    OpenFileDialog saveFileDialogBrowse = new OpenFileDialog();
    saveFileDialogBrowse.Filter = "Pcap file|*.pcap";
    saveFileDialogBrowse.Title = "Save an pcap File";
    saveFileDialogBrowse.ShowDialog();
    var pcapFile = saveFileDialogBrowse.FileName; //do whatever you like with the selected filename

    if (pcapFile != "")
    {
        FileInfo fileInfo = new FileInfo(pcapFile);
        txtFilePath.Text = fileInfo.FullName;
    }
}

【问题讨论】:

标签: c#


【解决方案1】:

没有简单的方法。

您可以使用File.Exists 检查路径上是否存在文件,但在执行下一行之前仍可能发生更改。您最好的选择是将File.Existstry-catch 结合起来以捕获任何可能的异常。

private void btnOpenFile_Click(object sender, EventArgs e)
{
    OpenFileDialog saveFileDialogBrowse = new OpenFileDialog();
    saveFileDialogBrowse.Filter = "Pcap file|*.pcap";
    saveFileDialogBrowse.Title = "Save an pcap File";
    saveFileDialogBrowse.ShowDialog();
    var pcapFile = saveFileDialogBrowse.FileName; //do whatever you like with the selected filename
    try
    {
        if (File.Exists(pcapFile))
        {
            FileInfo fileInfo = new FileInfo(pcapFile);
            txtFilePath.Text = fileInfo.FullName;
        }
    }
    catch (FileNotFoundException fileNotFoundException)
    {
        //Log and handle
    }
    catch (Exception ex)
    {
        //log and handle
    }
}

【讨论】:

    【解决方案2】:

    您可以使用File.Exists 方法,该方法记录在here

    【讨论】:

      【解决方案3】:

      你可以使用File.Exists方法:

      string fullPath = @"c:\temp\test.txt";
      bool fileExists = File.Exists(fullPath);
      

      【讨论】:

        猜你喜欢
        • 2011-10-09
        • 2014-06-30
        • 2014-08-08
        • 1970-01-01
        • 2016-05-09
        • 2013-01-06
        • 2011-09-06
        • 1970-01-01
        相关资源
        最近更新 更多