【问题标题】:Read from a JSON file inside a project从项目内的 JSON 文件中读取
【发布时间】:2021-03-03 17:22:06
【问题描述】:

我的 WPF 项目中有一个名为 Resources 的目录,并且该目录中有一个 Settings.json。 我想从该文件中读取内容。 在文件设置中,我有 Build Action -> Embedded ResourceCopy to Output Directory -> Copy Always 我读了这样的文件:

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

我得到以下异常:

{"找不到路径'C:\Resources\Settings.json'的一部分。"}

我怎样才能让它读取该目录中的文件?谢谢

【问题讨论】:

  • 什么类型的应用程序?在控制台应用程序中,这会将您带到 \bin 目录:AppDomain.CurrentDomain.BaseDirectory
  • @Icryder WPF 应用程序。

标签: c# visual-studio


【解决方案1】:

由于您已将 Build Action 设置为 Embedded Resource,因此您可能希望使用 Assembly.GetManifestResourceStream 方法。

例如:

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

【讨论】:

    【解决方案2】:
    using (StreamReader r = new StreamReader(Application.StartupPath + @"/Resources/Settings.json"))
    

    【讨论】:

    • “System.Windows.Application”不包含“StartupPath”的定义
    • 我猜这仅对 Windows 窗体应用程序有效。
    • System.AppDomain.CurrentDomain.BaseDirectory 用于 WPF 应用程序。
    • 在 ASP.NET 应用程序中会怎样?
    【解决方案3】:
    Directory.GetCurrentDirectory();
    

    【讨论】:

      【解决方案4】:

      对于 .Net Core 项目,将这些行添加到您的 .csproj 文件中:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-11-27
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多