简体   繁体   English

从项目内的 JSON 文件中读取

[英]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.我的 WPF 项目中有一个名为Resources的目录,该目录中有一个Settings.json 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 :在文件设置中,我有Build Action -> Embedded Resource and Copy to Output Directory -> Copy Always我像这样读取文件:

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'."} {“找不到路径 'C:\\Resources\\Settings.json' 的一部分。”}

How can I make this read the file in that directory?我怎样才能让它读取该目录中的文件? Thanks谢谢

Since you've got your Build Action set to Embedded Resource, you probably want to use the Assembly.GetManifestResourceStream method.由于您已将 Build Action 设置为 Embedded Resource,您可能希望使用Assembly.GetManifestResourceStream方法。

For example:例如:

using (Stream stream = assembly.GetManifestResourceStream("MyCompany.Namespace.Settings.json"))
using (StreamReader reader = new StreamReader(stream))
using (StreamReader r = new StreamReader(Application.StartupPath + @"/Resources/Settings.json"))
Directory.GetCurrentDirectory();

For .Net Core project add these lines to your .csproj file:对于 .Net Core 项目,将这些行添加到您的.csproj文件中:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM