我dll
用Cmdlet
命令创建了一个(参见 Get_DemoNames.cs)。从这里cmdlet
我称之为方法UpdateXml()
,到目前为止一切正常。但UpdateXml()
如果文件不存在,也会创建文件。当我UpdateXml()
像这样调用类文件时:
var parser = new Parser();
parser.UpdateXml();
我运行项目,它进入正确的目录。
但是,如果我加载导入的 dll 并DemoNames
在单独的测试项目中运行命令,如下所示:
PM> Import-Module C:\projects\EF.XML\EF.XML.dll
PM> DemoNames
程序转到错误的目录,导致以下错误:
Get-DemoNames:拒绝访问路径“C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\beheer_extern\config”。在 line:1 char:10 + DemoNames <<<< + CategoryInfo : NotSpecified: (:) [Get-DemoNames], UnauthorizedAccessException + FullyQualifiedErrorId : System.UnauthorizedAccessException,EF.XML.Get_DemoNames
我在网上搜索了这个错误,发现其他人可以通过将这一行添加到构造函数来解决它:
public Parser()
{
AppDomain.CurrentDomain.SetData("APPBASE", Environment.CurrentDirectory);
}
这给了我另一个错误的路径:
Get-DemoNames :拒绝访问路径“C:\Windows\system32\beheer_extern\config”。在 line:1 char:10 + DemoNames <<<< + CategoryInfo : NotSpecified: (:) [Get-DemoNames], UnauthorizedAccessException + FullyQualifiedErrorId : System.UnauthorizedAccessException,EF.XML.Get_DemoNames
Get_DemoNames.cs
namespace EF.XML
{
using System;
using System.Linq;
using System.Management.Automation;
[Cmdlet(VerbsCommon.Get, "DemoNames")]
public class Get_DemoNames : PSCmdlet
{
[Parameter(Position = 0, Mandatory = false)]
public string prefix;
protected override void ProcessRecord()
{
var names = new[] { "Chris", "Charlie", "Isaac", "Simon" };
if (string.IsNullOrEmpty(prefix))
{
WriteObject(names, true);
}
else
{
var prefixed_names = names.Select(n => prefix + n);
WriteObject(prefixed_names, true);
}
System.Diagnostics.Debug.Write("hello");
var parser = new Parser();
parser.UpdateXml();
}
}
}
解析器.cs
public class Parser
{
public void UpdateXml()
{
var directoryInfo = new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory); // www directory
var path = Path.Combine(directoryInfo.FullName, @"beheer_extern\config");
//Creates the beheer_extern\config directory if it doesn't exist, otherwise nothing happens.
Directory.CreateDirectory(path);
var instellingenFile = Path.Combine(path, "instellingen.xml");
var instellingenFileDb = Path.Combine(path, "instellingenDb.xml");
//Create instellingen.xml if not already existing
if (!File.Exists(instellingenFile))
{
using (var writer = XmlWriter.Create(instellingenFile, _writerSettings))
{
var xDoc = new XDocument(
new XElement("database", string.Empty, new XAttribute("version", 4)));
xDoc.WriteTo(writer);
}
}
}
}
如何获得项目的正确目录(www 目录)?