how to find that whether the file exist or not using c#

时间:2016-03-02 10:54:14

标签: c# .net

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);
            }

I want to search the file but it is not taking the the path that I am giving in File.Exixts() function what to do?

1 个答案:

答案 0 :(得分:0)

Thats probably because your path is not correct.

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

You need to check what is the value in your textBox1.Text and then you can concatenate the value with "*/" and .txt. It doesnt look to me as a valid path.

EDIT:

You can try like this if you are looking for a file in all the subdirectory

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