nandini336
nandini336

Reputation: 55

How to get relative path of the file that is exist in project folder in .net core project

I want to get a file path that is there in project file.

I tried

var path = @"Helper\automationJson.json"

but this getting the file from bin/debug as C:\AutomationActivityTrace\bin\Debug\netcoreapp2.2\Helper\automationJson.json

Also tried

string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, subfolder name, filename); 

and many more but I am not getting exactly what I want.

I need the path as C:\AutomationActivityTrace\Helper\automationJson.json

Can anyone help?!

Upvotes: 2

Views: 11598

Answers (1)

user3456014
user3456014

Reputation:

Assumption: your app needs to read this specific file and the file is present at build time.

You'll need to copy it to the bin folder as part of your build. This is done in your csproj file using CopyToOputputDirectory.

For example:

<Project Sdk="Microsoft.NET.Sdk">
   <!-- other stuff -->

  <ItemGroup>
    <None Include="Helper\*.json">
      <CopyToOutputDirectory>Always</CopyToOutputDirectory>
    </None>
  </ItemGroup>

</Project>

Now when you build the project, say with dotnet build, you should get a copy in C:\AutomationActivityTrace\bin\Debug\netcoreapp2.2\Helper\automationJson.json

The solutions involving AppContext.BaseDirectory should then find the file, for example Path.Combine(AppContext.BaseDirectory, "Helper", "automationJson.json")

Upvotes: 6

Related Questions