jason
jason

Reputation: 7164

Read from a JSON file inside a project

I have a directory named Resources in my WPF project and I have a Settings.json inside that directory. I want to read content from that file. In file settings I have Build Action -> Embedded Resource and Copy to Output Directory -> Copy Always And I read the file like this :

using (StreamReader r = new StreamReader(@"/Resources/Settings.json"))

And I get the following exception :

{"Could not find a part of the path 'C:\Resources\Settings.json'."}

How can I make this read the file in that directory? Thanks

Upvotes: 11

Views: 40349

Answers (4)

Dmitry Stepanov
Dmitry Stepanov

Reputation: 2914

For .Net Core project add these lines to your .csproj file:

<ItemGroup>
    <Content Include="Resources\**\*">
      <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
    </Content>
  </ItemGroup>

Upvotes: 1

sakir
sakir

Reputation: 3502

Directory.GetCurrentDirectory();

Upvotes: 2

Switchbreak
Switchbreak

Reputation: 126

Since you've got your Build Action set to Embedded Resource, you probably want to use the Assembly.GetManifestResourceStream method.

For example:

using (Stream stream = assembly.GetManifestResourceStream("MyCompany.Namespace.Settings.json"))
using (StreamReader reader = new StreamReader(stream))

Upvotes: 11

Sefa
Sefa

Reputation: 8992

using (StreamReader r = new StreamReader(Application.StartupPath + @"/Resources/Settings.json"))

Upvotes: 9

Related Questions