简体   繁体   中英

C# How to derive the relative-filepath of file located in grand-parent folder?

I am using Visual Studio 2005, (.NET version > 2.0+) to create a windows application.

As per my observation, the relative path of a file can be given in reference of EXE file created in DEBUG folder. example : if I give path as "images\\image.png" the file inside the folder "images" (which inturn located in DEBUG folder) is loaded.

my question is, what if the file exists in a parent folders? suppose that .. "DEBUG" resides in a "BIN" folder and that has one more folder "IMAGES" which I have to point in my code.
(bin/images/image.png)

this need can be avoided by copying "IMAGES" folder inside debug folder itself or by giving the absolute path, but .. I want to know if there is any way to point Parent folders in relative path

doesn't ".." work? as in, ../../image.png ?

edit to add some detail: as per MSDN , "A path is also said to be relative if it contains "double-dots"; that is, two periods together in one component of the path. This special specifier is used to denote the directory above the current directory, otherwise known as the "parent directory"."

two of these 'double-dots' would get you the grand-parent folder, as in my example.

.. is an alias for the parent folder of the current folder. Given your example, the path from the 'Debug' folder to the 'images' folder would be ..\\images .

You can use code like the following to verify what has been said:

DirectoryInfo dir = new DirectoryInfo("../..");
String name = dir.FullName;

Using .. allows you to move up the directory tree, from which you can then navigate down into the appropriate subdirectory.

i strongly suggest read about how CLR(runtime) locate dependencies? as well as probing in .net

On the post build event of the application, you may want to package the code such that you can create folders such as

  1. bin
    |-> Debug |-> Release
  2. images
  3. and so on...

Once this is in place, you can use relative paths from Debug or Release such as ../../images/file and so on.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM