-4

I want to check if a file exists in a directory or a sub-directory.

string[] filePaths = Directory.GetFiles(padserver, "*", SearchOption.AllDirectories);
try {
    DataContainer.bestaatal = false;
    lusfilebestaat = 0;
    while (DataContainer.bestaatal == false) {
        filePaths[lusfilebestaat] = Path.GetFileName(filePaths[lusfilebestaat]);
        if (filePaths[lusfilebestaat] == bestandsnaam) {
            DataContainer.bestaatal = true;
        }
        lusfilebestaat = lusfilebestaat + 1;
    }
}

This works but is to slow because I have much files on my server.

Is there anyone that have a solution for this?

Adi
  • 5,089
  • 6
  • 33
  • 47
Joeri
  • 1
  • 1
  • 4

2 Answers2

2

use System.IO.File.Exists() method. See msdn.

Sina Iravanian
  • 16,011
  • 4
  • 34
  • 45
  • whil this also scan in subdirectories? – Joeri Apr 15 '13 at 10:26
  • @Joeri the path you provide for it must be complete. – Sina Iravanian Apr 15 '13 at 10:27
  • @Joeri You have to pass on the file's path. `test.txt` definitely won't search subdirectories for you. – Nolonar Apr 15 '13 at 10:28
  • I have more than 100 subfolder. Tis does not work then? – Joeri Apr 15 '13 at 10:29
  • @Joeri What exactly are you trying to do? Search for a specific file from which you don't know where it is? In that case, "slow" is something you'll have to live with (unless your server has lots of SSDs). If you know where it's supposed to be, however, this is the best answer there is. – Nolonar Apr 15 '13 at 10:30
  • @Joeri do you have the sub-directories? Please edit your question and make it more clear so that we know what you exactly want. If you have sub directory names, you can use `Path.Combine` to build the full file name. – Sina Iravanian Apr 15 '13 at 10:31
0

This might help you

internal static bool FileOrDirectoryExists(string name)
{
   return (Directory.Exists(name) || File.Exists(name))
}

Or The alternative is to write the search function yourself, one of these should work:

private bool FileExists(string rootpath, string filename)
{
    if(File.Exists(Path.Combine(rootpath, filename)))
        return true;

    foreach(string subDir in Directory.GetDirectories(rootpath, "*", SearchOption.AllDirectories))
    {
        if(File.Exists(Path.Combine(rootpath, filename)))
        return true;
    }

    return false;
}

private bool FileExistsRecursive(string rootPath, string filename)
{
    if(File.Exists(Path.Combine(rootPath, filename)))
        return true;

    foreach (string subDir in Directory.GetDirectories(rootPath))
    {
        return FileExistsRecursive(subDir, filename);
    }

    return false;
}

The first still pulls out all of the directory names first so could be slow if there are lots of subdirectories and the file is close to the top.

The second is recursive, may be slower in 'worst case' scenarios but would be faster if there are many nested subdir and the file is in a top level dir.

Shrivallabh
  • 2,863
  • 2
  • 27
  • 47