资源(resx)查找返回不返回内容

问题描述 投票:0回答:1

我创建了一个需要嵌入外部文本文件的.net核心类库。我已将Resource.resx添加到项目根目录,并将我的文本文件添加到resx。我现在可以通过代码访问文本文件

var a = Resource.MyTxtResourceFile

intellisense让我知道MyTxtResourceFile“查找类似于[文件的正确内容]的本地化字符串

当我运行代码时,Resource.MyTxtResourceFile实际上返回了字符串

directory1\directory2\mytxtresourcefile.txt;System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089;utf-8

不是文本文件的内容。

Resource.Designer看起来像这样

/// <summary>
///    Looks up a localized string similar to [the contents of my text file]
/// </summary>
public static string MyTxtResourceFile {
    get {
        return ResourceManager.GetString("MyTxtResourceFile ", resourceCulture);
    }
}

有人可以帮忙吗?

.net-core embedded-resource
1个回答
1
投票

我不再直接将内容添加到resx文件中。我只是在项目中包含文本文件并使用GetManifestResourceStream方法获取内容,然后使用StreamReader将流转换为字符串。

例如,我有一个名为Stamina.World.DataAccess.SqlClient的项目。在子文件夹ReadAll.sql中有一个名为AuthenticationAttempt\Script的文件。我想获取该文件的内容。这是代码

var manifestResourceName = "Stamina.World.DataAccess.SqlClient.AuthenticationAttempt.Script.ReadAll.sql";

var contents = string.Empty;

// this assumes the file is in the current assembly
var currentAssembly = this.GetType().Assembly;

using (var manifestResourceStream = currentAssembly.GetManifestResourceStream(manifestResourceName))
{
    if (manifestResourceStream == null)
    {
        // TODO : handle this
    }

    using (var streamReader = new System.IO.StreamReader(manifestResourceStream))
    {
        contents = streamReader.ReadToEnd();
    }
}

// do something with the file contents
© www.soinside.com 2019 - 2024. All rights reserved.