C# T4 CustomHost错误空路径System.IO.FileStream.Init

C# T4 CustomHost错误空路径System.IO.FileStream.Init,c#,.net,t4,C#,.net,T4,正在尝试从中使用T4自定义主机,并根据产生的错误对其进行了调整,最后给出了底部的代码。当尝试像这样使用自定义主机时 var host = new CustomHost { TemplateFile = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "SimpleDate.tt"), CurrentAppDomain = AppDomain.CurrentDomain

正在尝试从中使用T4自定义主机,并根据产生的错误对其进行了调整,最后给出了底部的代码。当尝试像这样使用自定义主机时

    var host = new CustomHost
    {
        TemplateFile = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "SimpleDate.tt"),
        CurrentAppDomain = AppDomain.CurrentDomain
    };

    var output = new Engine().ProcessTemplate(File.ReadAllText(host.TemplateFile), host);

    if (host.Errors.HasErrors) throw new Exception(host.Errors[0].ErrorText);
。。。它返回以下错误

System.Exception
  HResult=0x80131500
  Message=An exception was thrown while trying to compile the transformation code. The following Exception was thrown:
System.ArgumentException: Empty path name is not legal.
   at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost)
   at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share)
   at Roslyn.Utilities.FileUtilities.OpenFileStream(String path)
   at Microsoft.CodeAnalysis.MetadataReference.CreateFromFile(String path, MetadataReferenceProperties properties, DocumentationProvider documentation)
   at Microsoft.VisualStudio.TextTemplating.CompilerBridge.<>c.<.ctor>b__15_0(String x)
   at System.Linq.Enumerable.WhereSelectListIterator`2.MoveNext()
   at System.Linq.Enumerable.<UnionIterator>d__67`1.MoveNext()
   at System.Linq.Enumerable.<UnionIterator>d__67`1.MoveNext()
   at System.Linq.Buffer`1..ctor(IEnumerable`1 source)
   at System.Linq.Enumerable.ToArray[TSource](IEnumerable`1 source)
   at System.Collections.Immutable.ImmutableArray.CreateRange[T](IEnumerable`1 items)
   at Microsoft.CodeAnalysis.ImmutableArrayExtensions.AsImmutableOrEmpty[T](IEnumerable`1 items)
   at Microsoft.CodeAnalysis.Compilation.ValidateReferences[T](IEnumerable`1 references)
   at Microsoft.CodeAnalysis.CSharp.CSharpCompilation.WithReferences(IEnumerable`1 references)
   at Microsoft.CodeAnalysis.CSharp.CSharpCompilation.CommonWithReferences(IEnumerable`1 newReferences)
   at Microsoft.VisualStudio.TextTemplating.CompilerBridge.PrepareNewCompilation()
   at Microsoft.VisualStudio.TextTemplating.CompilerBridge.Compile()
   at Microsoft.VisualStudio.TextTemplating.TransformationRunner.Compile(String source, String inputFile, IEnumerable`1 references, Boolean debug, SupportedLanguage language, String compilerOptions)
System.Exception
HResult=0x80131500
Message=尝试编译转换代码时引发异常。引发了以下异常:
System.ArgumentException:空路径名不合法。
在System.IO.FileStream.Init(字符串路径、文件模式、文件访问权限、Int32权限、布尔用户权限、文件共享、Int32缓冲大小、文件选项选项、安全属性secAttrs、字符串msgPath、布尔bFromProxy、布尔useLongPath、布尔checkHost)
位于System.IO.FileStream..ctor(字符串路径、文件模式、文件访问访问、文件共享)
位于Roslyn.Utilities.FileUtilities.OpenFileStream(字符串路径)
位于Microsoft.CodeAnalysis.MetadataReference.CreateFromFile(字符串路径、MetadataReferenceProperties属性、DocumentationProvider文档)
在Microsoft.VisualStudio.TextTemplating.CompilerBridge.c.b_uu15_0(字符串x)上
位于System.Linq.Enumerable.WhereSelectListIterator`2.MoveNext()
在System.Linq.Enumerable.d_u67`1.MoveNext()中
在System.Linq.Enumerable.d_u67`1.MoveNext()中
在System.Linq.Buffer`1..ctor处(IEnumerable`1源)
at System.Linq.Enumerable.ToArray[TSource](IEnumerable`1源)
位于System.Collections.Immutable.ImmutableArray.CreateRange[T](IEnumerable`1项)
位于Microsoft.CodeAnalysis.ImmutableArrayExtensions.AsImmutableOrEmpty[T](IEnumerable`1项)
在Microsoft.CodeAnalysis.Compilation.ValidateReferences[T](IEnumerable`1引用)
位于Microsoft.CodeAnalysis.CSharp.CSharpCompilation.WithReferences(IEnumerable`1参考)
在Microsoft.CodeAnalysis.CSharp.CSharpCompilation.CommonWithReferences上(IEnumerable`1 newReferences)
在Microsoft.VisualStudio.TextTemplating.CompilerBridge.PrepareNewCompilation()上
在Microsoft.VisualStudio.TextTemplating.CompilerBridge.Compile()上
在Microsoft.VisualStudio.TextTemplating.TransformationRunner.Compile(字符串源、字符串输入文件、IEnumerable`1引用、布尔调试、支持的语言、字符串编译器选项)
我不确定这个错误想告诉我什么。提供了一个包含内容的模板文件,非常简单,只在文本文件中生成日期。将模板包含在VS项目中会生成文本文件,因此该模板有效。谁能告诉我我做错了什么?我的客户主机有什么问题吗

using System;
using System.IO;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Text;
using Microsoft.VisualStudio.TextTemplating;
using System.Diagnostics;
using System.Linq;

namespace TTPlay
{
    public class CustomHost : ITextTemplatingEngineHost
    {
        public string TemplateFile { get; set; }
        public string FileExtension { get; set; } = ".txt";
        public Encoding FileEncoding { get; set; } = Encoding.UTF8;

        public IList<string> StandardAssemblyReferences { get; set; } = new string[]
        {
            typeof(System.Uri).Assembly.Location,
        };

        public IList<string> StandardImports { get; set; } = new List<string>
        {
            "System",
            "System.IO.FileSystem",
        };

        public bool LoadIncludeText(string requestFileName, out string content, out string location)
        {
            content = System.String.Empty;
            location = System.String.Empty;

            if (File.Exists(requestFileName))
            {
                content = File.ReadAllText(requestFileName);
                return true;
            }
            else
            {
                return false;
            }
        }

        public object GetHostOption(string optionName)
        {
            object returnObject;
            switch (optionName)
            {
                case "CacheAssemblies":
                    returnObject = true;
                    break;
                default:
                    returnObject = null;
                    break;
            }
            return returnObject;
        }

        public string ResolveAssemblyReference(string assemblyReference)
        {
            if (File.Exists(assemblyReference))
            {
                return assemblyReference;
            }

            string candidate = Path.Combine(Path.GetDirectoryName(this.TemplateFile), assemblyReference);
            if (File.Exists(candidate))
            {
                return candidate;
            }

            return "";
        }

        public Type ResolveDirectiveProcessor(string processorName)
        {
            if (string.Compare(processorName, "XYZ", StringComparison.OrdinalIgnoreCase) == 0)
            {
                //return typeof();
            }
            throw new Exception("Directive Processor not found");
        }

        public string ResolvePath(string fileName)
        {
            if (fileName == null) { throw new ArgumentNullException("the file name cannot be null"); }

            if (File.Exists(fileName)) { return fileName; }

            if (!string.IsNullOrWhiteSpace(this.TemplateFile))
            {
                string candidate = Path.Combine(Path.GetDirectoryName(this.TemplateFile), fileName);
                if (File.Exists(candidate))
                {
                    return candidate;
                }
            }

            return fileName;
        }

        public string ResolveParameterValue(string directiveId, string processorName, string parameterName)
        {
            if (directiveId == null)
            {
                throw new ArgumentNullException("the directiveId cannot be null");
            }
            if (processorName == null)
            {
                throw new ArgumentNullException("the processorName cannot be null");
            }
            if (parameterName == null)
            {
                throw new ArgumentNullException("the parameterName cannot be null");
            }

            return String.Empty;
        }

        public void SetFileExtension(string extension) => FileExtension = extension;
        public void SetOutputEncoding(Encoding encoding, bool fromOutputDirective) => FileEncoding = encoding;
        public void LogErrors(CompilerErrorCollection errors) => this.Errors = errors;
        public CompilerErrorCollection Errors { get; set; }
        public AppDomain ProvideTemplatingAppDomain(string content) => CurrentAppDomain;

        private AppDomain _currentAppDomain = null;
        public AppDomain CurrentAppDomain
        {
            get => _currentAppDomain;
            set
            {
                _currentAppDomain = value;

                // get assembly directories
                foreach (var assembly in _currentAppDomain.GetAssemblies())
                {
                    var directory = System.IO.Path.GetDirectoryName(assembly.Location);
                    if (!AssemblyDirectories.Any(x => x.FullName == directory))
                    {
                        AssemblyDirectories.Add(new DirectoryInfo(directory));
                    }
                }
            }
        }

        public List<DirectoryInfo> AssemblyDirectories = new List<DirectoryInfo>();
    }
}
使用系统;
使用System.IO;
使用System.CodeDom.Compiler;
使用System.Collections.Generic;
使用系统文本;
使用Microsoft.VisualStudio.TextTemplateing;
使用系统诊断;
使用System.Linq;
命名空间TTPlay
{
公共类CustomHost:ITextTemplatingEngineHost
{
公共字符串模板文件{get;set;}
公共字符串文件扩展名{get;set;}=“.txt”;
公共编码文件编码{get;set;}=Encoding.UTF8;
公共IList StandardAssemblyReferences{get;set;}=新字符串[]
{
typeof(System.Uri).Assembly.Location,
};
公共IList StandardImports{get;set;}=新列表
{
“系统”,
“System.IO.FileSystem”,
};
public bool LoadIncludeText(字符串请求文件名、输出字符串内容、输出字符串位置)
{
content=System.String.Empty;
位置=System.String.Empty;
if(File.Exists(requestFileName))
{
content=File.ReadAllText(requestFileName);
返回true;
}
其他的
{
返回false;
}
}
公共对象GetHostOption(字符串选项名称)
{
对象返回对象;
开关(选项名称)
{
案例“缓存程序集”:
returnObject=true;
打破
违约:
returnObject=null;
打破
}
返回对象;
}
公共字符串ResolveAssemblyReference(字符串assemblyReference)
{
if(File.Exists(assemblyReference))
{
返回集合引用;
}
字符串候选者=Path.Combine(Path.GetDirectoryName(this.TemplateFile),assemblyReference);
如果(文件存在(候选))
{
返回候选人;
}
返回“”;
}
公共类型ResolveDirectiveProcessor(字符串处理器名称)
{
if(string.Compare(processorName,“XYZ”,StringComparison.OrdinalIgnoreCase)==0)
{
//返回typeof();
}
抛出新异常(“未找到指令处理器”);
}
公共字符串解析路径(字符串文件名)
{
如果(fileName==null){抛出新的ArgumentNullException(“文件名不能为null”);}
如果(File.Exists(fileName)){return fileName;}
如果(!string.IsNullOrWhiteSpace(this.TemplateFile))
{
字符串候选者=Path.Combine(Path.GetDirectoryName(this.TemplateFile),文件名);
如果(文件存在(候选))
{
返回候选人;
}
}
返回文件名;
}
公共字符串ResolveParameterValue(字符串directiveId、字符串processorName、字符串parameterName)
{
if(directiveId==null)
{
抛出新ArgumentNullException(“directiveId不能为null”);
}
if(processorName==null)
{
抛出新ArgumentNullException(“processorName不能为null”);
}
    public IList<string> StandardAssemblyReferences { get; set; } = new string[]
    {
        typeof(System.Uri).Assembly.Location,
        "System.IO.FileSystem.dll",
    };

    public IList<string> StandardImports { get; set; } = new List<string>
    {
        "System",
    };