Dolphin
Dolphin

Reputation: 38601

How to get the file relative path in c# service project?

I have this code:

Stream stream = new StreamReader("~/quartz.xml").BaseStream;

Q1:What is the "~" symbol specify path in C#?

Q2:How to get the "~" directory in C# service project?

Q3:Does it mean the bin exe directory or project name directory?

The quartz.xml file in my Windows service project located in two position:

D:\jsptpd\Code\jsptpdJobScheduler\jsptpdJobScheduler\bin\Debug

D:\jsptpd\Code\jsptpdJobScheduler\jsptpdJobScheduler

Sure the path will change everytime!So get the relative path is better.

Upvotes: 0

Views: 2496

Answers (2)

Dolphin
Dolphin

Reputation: 38601

if we use(../quartz.xml):

the StreamReader read path is(not the file actual path):

C:\Windows\quartz.xml

if we use(quartz.xml):

the StreamReader read path is(not the file actual path):

C:\Windows\system32\quartz.xml

This is the way to find the file relative path:

                string assemblyFilePath = Assembly.GetExecutingAssembly().Location;
                string assemblyDirPath = Path.GetDirectoryName(assemblyFilePath);
                string configFilePath = assemblyDirPath + "\\quartz.xml";
                Stream stream = new StreamReader(configFilePath).BaseStream;

So the path is(you can specify either of two):

D:\jsptpd\Code\jsptpdJobScheduler\jsptpdJobScheduler\bin\Debug\quartz.xml

Upvotes: 1

Danny Beckett
Danny Beckett

Reputation: 20850

Just omit it entirely:

Stream stream = new StreamReader("quartz.xml").BaseStream;

The default directory is the .exe's directory.


Per the OP's edit to the question:

Go to View > Solution Explorer. Right-click the file in question, then choose Properties. Change the Copy To Output Directory option to Copy Always. Then use the code above.

Upvotes: 3

Related Questions