如何使用 C# 查找文件是否存在

本文关键字:是否 存在 文件 查找 何使用 | 更新日期: 2023-09-27 18:36:59

private void button1_Click(object sender, EventArgs e)
    {
        FolderBrowserDialog FldrBrowseDlg = new FolderBrowserDialog();
        FldrBrowseDlg.ShowNewFolderButton = true;
        DialogResult DigRslt = FldrBrowseDlg.ShowDialog();
        if (DigRslt.Equals(DialogResult.OK))
        {
            textBox1.Text = FldrBrowseDlg.SelectedPath;
            Environment.SpecialFolder rootfolder = FldrBrowseDlg.RootFolder;
        }
    }
    private void button2_Click(object sender, EventArgs e)
    {
        DirectoryInfo dir = new DirectoryInfo(textBox1.Text);
        FileInfo[] files = dir.GetFiles("*doc.zip", SearchOption.AllDirectories);
        foreach (FileInfo fl in files)
        {
            string s1 = fl.ToString();
            string name = s1.Substring(0, 28);
            string kyrname = name + ".txt";
            if (File.Exists(textBox1.Text+"*/"+kyrname))
            {
                label1.Text = "have kyrplus";
            }
            else
            {
                listBox1.Items.Add(name);
            }

我想搜索文件,但它没有采用我在函数中给出的路径File.Exixts()该怎么办?

如何使用 C# 查找文件是否存在

这可能是因为你的路径不正确。

File.Exists(textBox1.Text+"*/"+kyrname)

您需要检查textBox1.Text中的值是什么,然后您可以将该值与 "*/".txt 连接起来。在我看来,这不是一条有效的路径。

编辑:

如果要在所有子目录中查找文件,可以尝试这样做

var file = Directory.GetFiles(textBox1.Text, kyrname, SearchOption.AllDirectories)
                    .FirstOrDefault();
if (file == null)
{
    // File does not exist
}