C# 从项目内的JSON文件读取
在我的WPF项目中有一个名为Resources的目录,在该目录中有一个Settings.json。 我想从那个文件中读取内容。 在文件设置中,我有构建操作->嵌入资源和复制到输出目录->始终复制 我是这样读文件的:C# 从项目内的JSON文件读取,c#,visual-studio,C#,Visual Studio,在我的WPF项目中有一个名为Resources的目录,在该目录中有一个Settings.json。 我想从那个文件中读取内容。 在文件设置中,我有构建操作->嵌入资源和复制到输出目录->始终复制 我是这样读文件的: using (StreamReader r = new StreamReader(@"/Resources/Settings.json")) 我得到以下例外情况: {“找不到路径“C:\Resources\Settings.json”的一部分。”} 如何使其读取该目录中的文件?谢谢
using (StreamReader r = new StreamReader(@"/Resources/Settings.json"))
我得到以下例外情况:
{“找不到路径“C:\Resources\Settings.json”的一部分。”}
如何使其读取该目录中的文件?谢谢因为您已经将构建操作设置为Embedded Resource,所以您可能想要使用该方法
using (StreamReader r = new StreamReader(Application.StartupPath + @"/Resources/Settings.json"))
例如:
using (Stream stream = assembly.GetManifestResourceStream("MyCompany.Namespace.Settings.json"))
using (StreamReader reader = new StreamReader(stream))
对于.Net核心项目,请将以下行添加到
.csproj
文件中:
<ItemGroup>
<Content Include="Resources\**\*">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
</ItemGroup>
保存最新
什么类型的应用程序?在控制台应用程序中,这将使您进入\bin目录:AppDomain.CurrentDomain。BaseDirectory@IcryderWPF应用程序。“System.Windows.application”不包含“StartupPath”的定义。我想这仅对WPF应用程序的Windows Forms applications.System.AppDomain.CurrentDomain.BaseDirectory有效。在ASP.NET中该如何定义应用
<ItemGroup>
<Content Include="Resources\**\*">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
</ItemGroup>