I am using VS 2005 (.net version > 2.0+) to create a windows application.
In my application I give relative path to access the file. the file might exist in any of the known folders (say 2 in number) images1, images2, I need to check out开发者_StackOverflow which filepath is correct and which isn't, using some if conditions and bool variables. accordingly I need to point and load that image in my form.How can I do this?
You're looking for the Path.Combine
and File.Exists
methods.
Using LINQ:
var actualPath = possiblePaths.Select(p => Path.Combine(p, relativePath))
.FirstOrDefault(File.Exists);
foreach (string folder in folders)
if (File.Exist(folder + filename)
dosomething
I sense this is related to C# How to derive the relative-filepath of file located in grand-parent folder? Please read the responses.
A trial and error method would prove to be expensive
Simply use System.IO.File.Exists where you feed it the path(s) and filename, if it returns true, the file is there.
You'll probably need to make use of File.Exists()
. Using this along with Directory.Exists()
you can traverse the file system and load the appropriate file from the appropriate location
You can check for the existence of a file with the System.IO.File.Exists(string path) method. If it's helpful, there's also an equivalent System.IO.Directory.Exists(string path).
ETA the following from comments:
=======================================================================
Preprocessor directives also provide a means by which code can be compiled conditionally based on the configuration. For example something like this will give you one type of behavior with a "debug" build and a different type of behavior with a "release" (well, any non-debug) build:
public void DoStuff()
{
#if DEBUG
// The stuff in this block only happens for a DEBUG build
#else
// The stuff in this block only happens for a non-debug build
#endif
}
精彩评论