我有一个要求,我必须做以下事情:
- 动态生成代码
- 将代码写入现有的 .cs 文件
- 我必须在类文件的最后两个大括号之前添加代码。
例如,类文件是:
namespace Stackoverflow
{
public class AskQuestion
{
public void Ask()
{
}
//Add the generated code here.
}
}
我尝试了以下代码:创建了一个类 FindBraceLocation
namespace DBInfo.Class
{
public class FindBraceLocation
{
private int _bracePositionInLine;
private int _noOfBraceFound;
private int _lineNoIndex;
private readonly string[] _fs;
public int LineNoIndex
{
get { return _lineNoIndex; }
set { _lineNoIndex = value; }
}
public int BracePositionInLine
{
get { return _bracePositionInLine; }
set { _bracePositionInLine = value; }
}
public int NoOfBraceFound
{
get { return _noOfBraceFound; }
set { _noOfBraceFound = value; }
}
public FindBraceLocation(string[] allLines)
{
_bracePositionInLine = -1;
_noOfBraceFound = 0;
_lineNoIndex = 0;
_fs = allLines;
}
public void SearchFileStringIndex()
{
int noOfLines = _fs.Length;
string line;
int lineCounter;
int pos2 = -1;
for (lineCounter = noOfLines - 1; lineCounter >= 0; lineCounter--)
{
line = _fs[lineCounter];
if (line.Trim().Length == 0)
{
continue;
}
pos2 = FindIndexOfBrace(line);
if (pos2 != -1)
break;
}
_lineNoIndex = lineCounter;
_bracePositionInLine = pos2;
}
public int FindIndexOfBrace(string line)
{
//int braceNo = _noOfBraceFound;
for (int counter = line.Length - 1; counter >= 0; counter--)
{
if (line[counter] == '}' && (++_noOfBraceFound == 2))
{
return counter;
}
}
return -1;
}
}
}
并使用以下方法将其写入文件:
protected void WriteToExistingGeneratedFile(string strInfo, string strPath)
{
string[] allLines = File.ReadAllLines(strPath);
FindBraceLocation fp = new FindBraceLocation(allLines);
fp.SearchFileStringIndex();
string lineForInsertion = allLines[fp.LineNoIndex];
string tempLine = lineForInsertion.Substring(0, fp.BracePositionInLine) + "\n" + strInfo + "\n" + lineForInsertion.Substring(fp.BracePositionInLine);
allLines[fp.LineNoIndex] = tempLine;
File.WriteAllLines(strPath, allLines);
}