how to create an output file only if it does not exist in t4 generator?

StackOverflow https://stackoverflow.com/questions/23307143

  •  09-07-2023
  •  | 
  •  

문제

I have a T4 generator like the following :

<#@ template language="C#" debug="false" hostspecific="true"#>
<#@ include file="EF6.Utility.CS.ttinclude"#>
<#@ import namespace="System.IO" #><#@ 
 output extension=".cs"#>
<#foreach (var entity in typeMapper.GetItemsToGenerate<EntityType>(itemCollection))
{
    var fileName = entity.Name + "Controller.cs";
    fileManager.StartNewFile(fileName);
}#>

I don't want T4 generator delete my modification so I need to stop generating during the file existed how is it possible ?

도움이 되었습니까?

해결책

You can use function DoesFileExist and check on while creating new file. If it is already exist then you can write same texts (existing file) with OutputFile

// Check for file existence
bool DoesFileExist(string filename)
{            
    return File.Exists(Path.Combine(GetCurrentDirectory(),filename));    
}
// Get current  folder directory
string GetCurrentDirectory()
{
    return System.IO.Path.GetDirectoryName(Host.TemplateFile);
}
// Get content of file name
string OutputFile(string filename)
{
    using(StreamReader sr = 
      new StreamReader(Path.Combine(GetCurrentDirectory(),filename)))
    {
        return sr.ReadToEnd();
    }
}

Writing same file:

// Write with original file
fileManager.StartNewFile(fileName);
this.Write(OutputFile(fileName));

You can refer this example Metadata Class or Data Annotation from EDMX Files

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top