Jimmy Collins
Jimmy Collins

Reputation: 3304

Search for the path to a file in C#

I need to access a file created at a random location in the %temp% directory, for example at a path like:

%temp%/[FSF480-3R3RC3-RDDWW-32FDF-3FD3E-]/files/test.txt

Can someone tell me how to search for, and return a path to 'test.txt' so I can open it to read data from it?

Thanks.

Upvotes: 0

Views: 9339

Answers (3)

Jeff Swensen
Jeff Swensen

Reputation: 3573

Directory.EnumerateFiles will let you search for files that match a pattern under a specific path, optionally searching subdirectories. The linked MSDN page shows usage.

Very similar question here where it is suggested to use Directory.GetFiles with the recursive option.

Directory.GetFiles(Path.GetTempPath(), "test.txt", SearchOption.AllDirectories) 

Use GetFiles() if you're searching for few results, EnumerateFiles() if your searching for many.

The EnumerateFiles and GetFiles methods differ as follows: When you use EnumerateFiles, you can start enumerating the collection of names before the whole collection is returned; when you use GetFiles, you must wait for the whole array of names to be returned before you can access the array. Therefore, when you are working with many files and directories, EnumerateFiles can be more efficient.

Upvotes: 4

Sören
Sören

Reputation: 2731

the GetCreationTime method may additionally help u to determine the right folder after using GetDirectories (see Oded's post) - I don't know whether u have any information about the directory name, if u do, it may be good to use a combination of both of them.

Upvotes: 0

Oded
Oded

Reputation: 499002

You can start by using Directory.GetDirectories for a recursive search through the directory tree and Directory.GetFiles to list the files in each.

This should allow you to find the file.

See this walkthrough on the Microsoft Support site.

Upvotes: 0

Related Questions