0

I am currently accessing the File by using the relative path, kindly refer the below code snippet.

var filePath = @"..\..\..\..\..\..\..\..\Common\Data";

When I build the project with ANYCPU it works fine,but when I change the configuration manager to x64 or x86 the file cannot be found because in bin folder the x64/x86 folder is created so that the file cannot be found. However, adding extra dots it works fine. Kindly refer the below snippet.

var filePath = @"..\..\..\..\..\..\..\..\..\Common\Data";

Can you please provide the solution that how to detect the configuration manager is x64/x86 programmatically in c#?

Paul Karam
  • 4,052
  • 8
  • 30
  • 53
Mohan Selvaraj
  • 236
  • 2
  • 15

2 Answers2

1

In such case you should consider moving the hard-coded path into config file. e.g. add below setting in your app.config or web.config

<appSettings>
    ...
    <add key="DataFilePath" value="..\..\..\..\..\..\..\..\Common\Data" />
    ...
</appSettings>

And then load the setting in codes:

var filePath = System.Configuration.ConfigurationManager.AppSettings["DataFilePath"];

The benefit of this approach is that it give you the flexibility to change the setting after application built. More over you could use the Web.config Transformation Syntax to define specific settings for each build configuration. (Though the example is using web.config , this tool actually work for app.config as well)

Evan Huang
  • 1,245
  • 9
  • 16
  • Hi,I am currently using the Windows forms application i am not using the app.config or web.config file in my sample application. – Mohan Selvaraj Jan 22 '18 at 07:20
  • you could create a settings-file and add via `Properties.Settings.Default...` - basically the same as shown above – Felix D. Jan 22 '18 at 07:23
1

You can use AppDomain.CurrentDomain.BaseDirectory, like below:

var filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "relativePath");
Feiyu Zhou
  • 4,344
  • 32
  • 36