gopal
gopal

Reputation: 3741

Environment.CurrentDirectory in C#.NET

The property Environment.CurrentDirectory always returns the path of system directory instead my application directory. In my colleague's PC, it returns application directory.

What is the problem? How can I solve it?

The following code is working for me

ePCRSettings = XMLParser.XmlParser.Deserialize<PCRGeneratorSettings>(string.Format("{0}\\ePCRPDFSettings.xml", AppDomain.CurrentDomain.BaseDirectory));

AppDomain.CurrentDomain.BaseDirectory - Returns the directory E:\MyApplications\.

The following code is not working for me

ePCRSettings = XMLParser.XmlParser.Deserialize<PCRGeneratorSettings>(string.Format("{0}\\ePCRPDFSettings.xml", Environment.CurrentDirectory));

Environment.CurrentDirectory - Returns c:\windows\system32.

This .dll file can be used in VB 6 and ASP.NET applications

Upvotes: 13

Views: 22344

Answers (4)

Sev
Sev

Reputation: 781

Use

System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location);

Upvotes: 7

Usman
Usman

Reputation: 151

set current directory

Directory.SetCurrentDirectory(AppDomain.CurrentDomain.BaseDirectory); //or set executing Assembly location path in param

Environment.CurrentDirectory //now returns your app path

Upvotes: 15

Calanus
Calanus

Reputation: 26257

I suspect that this could have something to do with the current user id that the app is running under, for example if you are running the app in a user session (e.g. debugging in VS) then this may return your current directory, but if you were running it under IIS then this could be why it is defaulting to the system folder?

Upvotes: 1

Gishu
Gishu

Reputation: 136603

You shouldn't be using the Environment.CurrentDirectory value as a base for file lookups because it can change and may not always be under your control. e.g. a File Save As to a different folder may change the 'current folder' value. As you can see it can yield unpredictable results.

Use a value that you can control better. e.g. a ResourcesFolderPath value in a configuration (xml?) file that is updated when you install your app.

Upvotes: 3

Related Questions