C#中:执行作为资源存储在SQL脚本脚本、资源、SQL

2023-09-04 08:42:19 作者:爱、不在服务区う

新手问题:我想存储漫长的.sql脚本在我的解决方案,并通过编程执行它们。我已经找到了如何执行包含我的SQL脚本一个字​​符串,但我还没有想出如何读取,将存储在解决方案文件中的字符串(下/脚本子文件夹为例)。

Newbie question : I would like to store lengthy .sql scripts in my solution and execute them programmatically. I've already figured out how to execute a string containing my sql script but I haven't figured out how to read the string from a file that would be stored in the solution (under a /Scripts subfolder for example).

非常感谢,

推荐答案

首先,这样它会被作为资源嵌入编辑.sql文件的属性。

First, edit the .sql file's properties so that it will be embedded as a resource.

然后用code类似于以下检索脚本:

Then use code similar to the following to retrieve the script:

string commandText;
Assembly thisAssembly = Assembly.GetExecutingAssembly();
using (Stream s = thisAssembly.GetManifestResourceStream(
      "{project default namespace}.{path in project}.{filename}.sql"))
{
   using (StreamReader sr = new StreamReader(s))
   {
      commandText = sr.ReadToEnd();
   }
}