Based on suggestion from AMercer, I wrote this recursive function:
public static string GetApplicationRoot()
{
return GetApplicationRootRecursive(Application.StartupPath);
}
private static string GetApplicationRootRecursive(string path)
{
if (Directory.GetParent(path) != null)
{
if (new DirectoryInfo(path).Name == Application.ProductName)
return path;
else
return
GetApplicationRootRecursive(Directory.GetParent(path).FullName);
}
return null;
}
Now I can call:
xmlDocument.Load(Utility.GetApplicationRoot() + @"\Settings\MyXMLFile.xml");
and it should work on both development and after deployment.
Thanks,
P_Prdn
[quoted text, click to view] "P_Prdn" wrote:
> I will try your suggestion. I think this will work. Thank you so much.
>
> P_Prdn
>
> "AMercer" wrote:
>
> > > I was wondering if somebody could show me on how to use relative path in
> > > windows application that will work during DEVELOPMENT as well as after
> > > DEPLOYMENT. In short, here's my situation. During development the files in my
> > > project are located as follows:
> > >
> > > MyProject\bin\Release\MyApplication.exe
> > > MyProject\Settings\MyXMLFile.xml
> > >
> > > During development I use this syntax to load to MyXMLFile.xml from the .exe:
> > >
> > > xmlDocument.Load(@"..\..\Settings\MyXMLFile.xml");
> > >
> > > Everything was fine until after I deployed the project whereas the file
> > > location now changed to:
> > >
> > > C:\Program Files\MyProject\MyApplication.exe
> > > C:\Program Files\MyProject\Settings\MyXMLFile.xml
> > >
> > > Now I started to get an error message stating that file
> > > 'C:\Settings\MyXMLFile.xml doesn't exist'.
> > >
> > > Please keep in mind these limitations:
> > >
> > > 1. I do not want to hard-code the relative path in app.config, I just want
> > > to use relative path.
> > > 2. I cannot use resource file because I need to change the MyXMLFile.xml
> > > during runtime.
> > > 3. Basically what I need is the relative path that can point to the project
> > > folder instead of the .exe, much like ~ sign to point to application root
> > > folder in web application.
> >
> > The way I've dealt with this problem is as follows:
> >
> > 1. Get the exe path, eg Application.ExecutablePath
> > 2. Remove the file name (at the tail)
> > 3. Search this directory (and all subdirectories) for the file you want
> > 4. If found, you are done, otherwise, back up to the parent and try again.
> > 5. Ditto, if necessary.
> >
> > In my worst case, I needed to go to step 5, and it looks like you will too.
> > In deployment you will find the file in step 3, and in development, you will
> > find it in step 5. Variables that contains the paths to your files
> > (MyXMLFile.xml etc) could all be initialized with a function that implements
> > the above logic.