对嵌入式资源的强类型访问



我正在尝试建立对在类库中创建的嵌入式SQL资源文件的访问权限。然而,我不确定从这里到哪里去。

我使用访问了资源

Assembly.GetExcecutingAssembly().GetManifestResourceStream("InsertTest.sql");

我的理解是,有一种方法可以以强类型的方式访问它们,但我似乎无法掌握项目或解决方案,无法用程序浏览它们各自的属性或资源。

我错过了什么?

尽管我确实得到了一些很棒的建议(请参阅Philip Daniels的回答——不错的东西),但没有一个真正解决我的具体问题。然而,我发现实现这一点最简单的方法是执行以下操作:

  1. 右键单击项目并选择"属性">
  2. 选择"资源"选项卡。如有必要,创建一个新的资源文件
  3. 在左上角有一个下拉菜单,默认为"Strings"。单击此框并选择"文件">
  4. 拖放要嵌入到项目中的资源文件

您现在可以使用以下语法访问强类型资源:

Project.Properties.Resources.ResourceName;

在我的情况下,这非常有效,因为我将内联SQL存储在这些文件中,并返回嵌入文件中的SQL。但是,请记住,默认情况下,这些资源是链接的,并且不是嵌入的,但您可以更改它们的属性以将它们设置为嵌入的。

希望这能帮助到别人!

您就快到了。我有几个函数用于此。你可以为图像做一些非常相似的事情。我不确定是否值得创建您想要的属性(如果您坚持,可以通过项目属性的"资源"选项卡进行创建)。

/// <summary>
/// Gets an open stream on the specified embedded resource. It is the
/// caller's responsibility to call Dispose() on the stream.
/// The filename is of the format "folder.folder.filename.ext"
/// and is case sensitive.
/// </summary>
/// <param name="assembly">The assembly from which to retrieve the Stream.</param>
/// <param name="filename">Filename whose contents you want.</param>
/// <returns>Stream object.</returns>
public static Stream GetStream(Assembly assembly, string filename)
{
string name = String.Concat(assembly.GetName().Name, ".", filename);
Stream s = assembly.GetManifestResourceStream(name);
return s;
}
/// <summary>
/// Get the contents of an embedded file as a string.
/// The filename is of the format "folder.folder.filename.ext"
/// and is case sensitive.
/// </summary>
/// <param name="assembly">The assembly from which to retrieve the file.</param>
/// <param name="filename">Filename whose contents you want.</param>
/// <returns>String object.</returns>
public static string GetFileAsString(Assembly assembly, string filename)
{
using (Stream s = GetStream(assembly, filename))
using (StreamReader sr = new StreamReader(s))
{
string fileContents = sr.ReadToEnd();
return fileContents;
}
}

在资源文件中,您将无法使用intellisense来构建sql脚本,而在项目中将它们作为单独的文件。您可以创建一个助手类来以强类型的方式访问它们:

public class Scripts
{
public static string Sql1
{
get
{
return GetResource("sql1.sql");
}
}
public static string Sql2
{
get
{
return GetResource("sql2.sql");
}
}
private static string GetResource(string name)
{
var assembly = Assembly.GetExecutingAssembly();
using(var stream = new StreamReader(assembly.GetManifestResourceStream("Myproject.Sql." + name)))
{
return stream.ReadToEnd();
}
}
}

例如,在Dapper中,您可以这样访问脚本:

using(var db = new SqlConnection("yourconnectionstring")){
db.Open();
var results = db.Query(Scripts.Sql1);
} 

最新更新