正如您所注意到的,您可以在 2008 年使用的VSTA 辅助方法在 2012 年被移动/删除。仍然可以这样做,但代码已更改。
最简单的做法是使用VstaHelper.LoadProjectFromFolder ()加载现有项目。
如果要动态添加脚本文件,请参见下面的代码片段。您需要记住两个主要事项:
ScriptingEngine 和 VstaHelper 类代表 VSTA 本身。这是您创建项目并添加新文件的地方。您不能在此处直接删除或替换现有文件。当您调用 SaveProjecToStorage() 时,就像关闭 VSTA 窗口一样……它将项目和编译后的二进制文件保存到 ScriptTask。
ScriptTask.ScriptStorage 允许您直接操作源文件内容。从这里,您可以修改文件的内容。
以下代码片段应该可以帮助您入门。
static void Main(string[] args)
{
// 1. Create new package, and add a script task
var pkg = new Package();
var exec = pkg.Executables.Add("STOCK:ScriptTask");
var th = (TaskHost)exec;
th.Name = "Script Task";
th.Description = "This is a Script Task";
var task = (ScriptTask)th.InnerObject;
// 2. Set the script language - "CSharp" or "VisualBasic"
task.ScriptLanguage = VSTAScriptLanguages.GetDisplayName("CSharp");
// 3. Set any variables used by the script
//task.ReadWriteVariables = "User::Var1, User::Var2";
// 4. Create a new project from the template located in the default path
task.ScriptingEngine.VstaHelper.LoadNewProject(task.ProjectTemplatePath, null, "MyScriptProject");
// 5. Initialize the designer project, add a new code file, and build
//task.ScriptingEngine.VstaHelper.Initalize("", true);
//task.ScriptingEngine.VstaHelper.AddFileToProject("XX.cs", "FileContents");
//task.ScriptingEngine.VstaHelper.Build("");
// 6. Persist the VSTA project + binary to the task
if (!task.ScriptingEngine.SaveProjectToStorage())
{
throw new Exception("Save failed");
}
// 7. Use the following code to replace the ScriptMain contents
var contents = File.ReadAllText("path to file");
var scriptFile =
task.ScriptStorage.ScriptFiles["ScriptMain.cs"] =
new VSTAScriptProjectStorage.VSTAScriptFile(VSTAScriptProjectStorage.Encoding.UTF8, contents);
// 8. Reload the script project, build and save
task.ScriptingEngine.LoadProjectFromStorage();
task.ScriptingEngine.VstaHelper.Build("");
// 9. Persist the VSTA project + binary to the task
if (!task.ScriptingEngine.SaveProjectToStorage())
{
throw new Exception("Save failed");
}
// 10. Cleanup
task.ScriptingEngine.DisposeVstaHelper();
// 11. Save
string xml;
pkg.SaveToXML(out xml, null);
File.WriteAllText(@"c:\temp\package.dtsx", xml);
}