tags:

views:

47

answers:

2

I included a text file as output in a WCF set up project. The text file is correctly located in the same folder with the dll, exe, and config file after the project is installed (C:\Program Files\KLTesting\KLTestApp). However when the program tries to read it, it looks under "C:\Windows\system32", what's the correct way to find & read it?

I have

string a = Directory.GetCurrentDirectory();
a += "/R0303.txt";
string content = File.ReadAllText(a);

Thanks.

A: 

You should use AppDomain.CurrentDomain.BaseDirectory or AppDomain.CurrentDomain.SetupInformation.ApplicationBase instead, to get the Directory of your .exe file.

BurningIce
A: 

First you should not call Directory.GetCurrentDirectory() and concatenate with the file name. The service is running within a web server like IIS or some other type of container, so GetCurrentDirectory will not give you what you are thinking as you found out. (On a quick tangent, as a recommendation in the future if you want to do path combining you should use Path.Combine method as it will handle all the corner cases and be cross platform.)

There are a few ways to do this:

Assembly myAssembly = Assembly.GetAssembly(SomeTypeInAssm.GetType());
string fullFileName = Path.Combine(myAssembly.Location, "MyFile.txt");

The fullFileName should be what you are looking for. Make sure you use a type that is actually in an assembly located and referenced from the directory in question. However be aware because this file in your question in the Program Files area this is a secure area on Vista and higher OS's and you may not have access to do anything but read the file.

Also you could have the installer of the application place in the registry the install path. Then your service if on the same box can pull this information.

Also you could make sure the file you want to load is within the web server environment that is accessable to the WCF service in question.

Rodney Foley
If you want the the assembly of the current executing code you can use Assembly.GetExecutingAssembly()
BurningIce
And btw, WCF is not at all limited to being hosted inside a asp.net application. A normal desktop application or windows service can also host a WCF endpoint.
BurningIce
@BurningIce I know WCF is not limited to being hosted in a ASP.net application, I didn't say that BTW either, I said in a web server as a WCF service does not have to even be ASP.net compatible. Regardless he stated GetCurrentDirectory returned System 32 which means a service is his entry point and is referencing the DLL in the location he does want. If he wants to find that location he needs to use Reflection to get the Assembly's location. Getting the AppDomain BaseDirectory will most likely still return System 32, as would GetExecutingAssembly in this case.
Rodney Foley