user584018
user584018

Reputation: 11304

What could be the best way to get file path

I have 3 different directories where files are available for further processing.

  1. May be some directory not exist, hence I put try/catch.
  2. As soon as a single file available in any directory, I am returning the path.

Here is below code, question, what could be the best way to get file path as above functionality?

private static string GetRealPath()
    {
        const string filePath1 = @"C:\temp1\";
        const string filePath2 = @"C:\temp2\";
        const string filePath3 = @"C:\temp\";

        //looks for file in  @"C:\temp1\ 
        try
        {
            if (Directory.EnumerateFileSystemEntries(filePath1, "*.txt").ToList().Count > 0)
            {
                return filePath1;
            }
        }
        catch (Exception e) { Console.WriteLine(e); }

        //looks for file in  @"C:\temp2\ 
        try
        {
            if (Directory.EnumerateFileSystemEntries(filePath2, "*.txt").ToList().Count > 0)
            {
                return filePath2;
            }
        }
        catch (Exception e) { Console.WriteLine(e); }

        //looks for file in  @"C:\temp\ 
        try
        {
            if (Directory.EnumerateFileSystemEntries(filePath3, "*.txt").ToList().Count > 0)
            {
                return filePath3;
            }
        }
        catch (Exception e) { Console.WriteLine(e); }

        return string.Empty;
    }

Upvotes: 0

Views: 91

Answers (1)

Tim Schmelter
Tim Schmelter

Reputation: 460018

You could use Directory.Exists instead:

public static string GetFirstValidPath()
{
    string[] paths = { @"C:\temp1\", @"C:\temp2\", @"C:\temp\"};
    return paths.FirstOrDefault(p=> Directory.Exists(p) 
       && Directory.EnumerateFileSystemEntries(p, "*.txt").Any()) ?? string.Empty;
}

Upvotes: 4

Related Questions