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