从Webservice动态创建的程序集 - 如何在运行时获取.CS代码?

时间:2013-07-04 15:38:55

标签: c# web-services dynamically-generated

我是从webservice动态创建程序集。在阅读初始响应流(WSDL)之后,我使用ServiceDescriptionImporter和ServiceDescription来获取流和CodeDomProvider进行编译。

进口商

ServiceDescriptionImporter descriptionImporter = new ServiceDescriptionImporter();
ServiceDescription serviceDescription = ServiceDescription.Read(xmlreader);
descriptionImporter.AddServiceDescription(serviceDescription, null, null);
descriptionImporter.Style = ServiceDescriptionImportStyle.Client;
descriptionImporter.CodeGenerationOptions = System.Xml.Serialization.CodeGenerationOptions.GenerateProperties;

汇编

CodeCompileUnit codeUnit = new CodeCompileUnit();
CodeNamespace codeNamespace = new CodeNamespace();
codeUnit.Namespaces.Add(codeNamespace);
ServiceDescriptionImportWarnings importWarnings = descriptionImporter.Import(codeNamespace, codeUnit);
if (importWarnings == 0) 
{          
    results = compiler.CompileAssemblyFromDom(parameters, codeUnit);
}

我现在得到一个在我的临时目录中创建的程序集,但我需要一个带有代码的.CS文件(就像wsdl.exe工具会创建的那样)。有没有办法不创建程序集而只有CS代码?

我可以在转换之前访问XML流,但这只是WSDL。我尝试从CodeDomProvider创建代码,但它只创建一个空文件

    private void CreateCSCode(string FilePathName, CodeDomProvider provider)
    {

        CodeGeneratorOptions options = new CodeGeneratorOptions();
        options.BracingStyle = "C";
        using (StreamWriter sourceWriter = new StreamWriter(FilePathName))
        {
            provider.GenerateCodeFromCompileUnit(new System.CodeDom.CodeCompileUnit(), sourceWriter, options);
        }
    }

1 个答案:

答案 0 :(得分:0)

您可以使用“GenerateCodeFromCompileUni”方法从compileUnit(而不是CodeDom)中提取代码:

TextWriter tw = new IndentedTextWriter(new StreamWriter(PathAndName + ".cs", false), "    ");
compiler.GenerateCodeFromCompileUnit(codeUnit, tw, new CodeGeneratorOptions());

然后你应该能够从创建的文件编译......