在两个大括号结束之前将文本写入.CS文件
本文关键字:文本 文件 CS 结束 两个 | 更新日期: 2023-09-27 17:56:48
我有一个要求,在其中我必须做以下事情:
- 动态生成代码
- 将代码写入现有.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);
}
动态生成第二个文件并使用 partial
关键字向类添加新成员,而不是修改现有文件。
静态文件:
namespace Stackoverflow
{
public partial class AskQuestion
{
public void Ask()
{
}
}
}
生成的文件:
namespace Stackoverflow
{
partial class AskQuestion
{
// Dynamically generated methods and properties
}
}
如果使用流读取器,则可以在其上使用普通的字符串函数。这样的东西会起作用:
System.IO.StreamReader myFile =
new System.IO.StreamReader("c:''test.cs");
string myString = myFile.ReadToEnd();
// This will error if there are not at least 2 parentheses.
string UpToLastParan = myString.Text.Substring(0, myString.LastIndexOf("}"));
int SecondToLast = UpToLastParan.LastIndexOf("}");
string UpToSecondToLastParan = myString.Substring(0, SecondToLast);
string CorrectedString = UpToSecondToLastParan + "Your Code Here" + myString.Substring(SecondToLast, myString.Length - SecondToLast);
// Write back to file.