读取嵌入.NET程序集的数据

Pie*_* A. 4 .net c# reflection dll

对于学校项目,我不允许使用存储过程来存储我的SQL脚本.为了解决这个问题,我试图在我的类程序集中创建一个SQL_scripts文件夹.

我的项目结构

现在我被困在如何从相对路径读取我的脚本?

在这里我尝试没有成功:

var appDomain = System.AppDomain.CurrentDomain;
                var basePath = appDomain.RelativeSearchPath ?? appDomain.BaseDirectory;
                string path = Path.Combine(basePath, "SQL_scriptes", "GetAllEmptyRoomsAtDateRange.sql");
                string query = File.ReadAllText(path);
Run Code Online (Sandbox Code Playgroud)

但我总是在以下文件夹中:

  • MyProject的\测试\ BIN \调试\ SQL_scriptes\GetAllEmptyRoomsAtDateRange.sql

任何的想法?

kma*_*zek 6

您应该使用sql代码作为嵌入资源添加文件:

在此输入图像描述

并使用以下函数从文件中获取SQL:

public string GetScript(string scriptName)
{
    var assembly = Assembly.GetExecutingAssembly();
    var resourceName = "Q46868043.SQL_scripts." + scriptName;

    using (Stream stream = assembly.GetManifestResourceStream(resourceName))
    using (StreamReader reader = new StreamReader(stream))
    {
        return reader.ReadToEnd();
    }
}
Run Code Online (Sandbox Code Playgroud)