开发者

Removing items in code generated from Codedom

开发者 https://www.devze.com 2023-01-11 03:34 出处:网络
Is there a way to remove items in code generated in Codedom from VB code? For example at the top of all the code I gener开发者_Go百科ate, it has:

Is there a way to remove items in code generated in Codedom from VB code?

For example at the top of all the code I gener开发者_Go百科ate, it has:

'------------------------------------------------------------------------------
' 
'     This code was generated by a tool.
'     Runtime Version:4.0.30319.1
'
'     Changes to this file may cause incorrect behavior and will be lost if
'     the code is regenerated.
' 
'------------------------------------------------------------------------------
Option Strict Off 
Option Explicit On 

I'd like both of these to go away - the commented text and the both the Option xxx. I've tried toying around with CodeGeneratorOptions, but have not been able to remove the above from generated code.


For #2, have you tried this?

CodeCompileUnit.UserData.Add("AllowLateBound", False) ' strict on
CodeCompileUnit.UserData.Add("RequireVariableDeclaration", False) ' explicit off

(where CodeCompileUnit is a variable of type CodeCompileUnit)


You can use a StringWriter to output your code, then use StringBuilder.Remove in order to delete the first lines:

using (var stringWriter = new StringWriter())
using (var streamWriter = new StreamWriter(path))
{
    codeDomProvider.GenerateCodeFromCompileUnit(unit, stringWriter, options);
    StringBuilder sb = stringWriter.GetStringBuilder();
    /* Remove the header comment (444 is for C#, use 435 for VB) */
    sb.Remove(0, 444);
    streamWriter.Write(sb);
}

It's ugly, but it works ™


No, that can't be removed. It is hard-coded into the VBCompiler. You can see this in system.dll in Reflector.


Here is my proposal inspired from Maxence's one, but maybe a bit "cleaner", as I'm using a regular expression instead of indexes that may vary over time. This should work for both C# and VB.net.

using (var stringWriter = new StringWriter())
using (var sourceWriter = new StreamWriter(fileName, false, Encoding.UTF8))
{
   codeDomProvider.GenerateCodeFromCompileUnit(CodeUnit, stringWriter, generatorOptions);
   var newContent = Regex.Replace(stringWriter.ToString(), @"^//.*Runtime Version:.*$", "//\r", RegexOptions.Multiline);
   sourceWriter.Write(newContent);
}
0

精彩评论

暂无评论...
验证码 换一张
取 消