C# 将文件加载到数组中,然后保存回文件
我试图将文件和内容加载到数组中,然后在文件中的某个位置添加一行。例如: 所以,将add行中的文件加载到此文件中,然后复制回数组并保存它。这是我到目前为止的代码,但我不确定如何重建它C# 将文件加载到数组中,然后保存回文件,c#,C#,我试图将文件和内容加载到数组中,然后在文件中的某个位置添加一行。例如: 所以,将add行中的文件加载到此文件中,然后复制回数组并保存它。这是我到目前为止的代码,但我不确定如何重建它 private void addgsc() { string[] lines = System.IO.File.ReadAllLines (modspath + "//maps//_zombiemode_weapons.gsc"); int index = -1
private void addgsc()
{
string[] lines = System.IO.File.ReadAllLines
(modspath + "//maps//_zombiemode_weapons.gsc");
int index = -1; // Where to insert the new line.
List<string> newLines = new List<string>();
for (int i = 0; i < lines.Length; i++)
{
newLines.Add(lines[i]);
if (lines[i].Contains("add_zombie_weapon"))
index = i + 1;
}
if (index > -1)
{
newLines.Insert(index, "test 21");
}
string[] rebulidarr = newLines.ToArray();
private void addgsc()
{
字符串[]行=System.IO.File.ReadAllLines
(modspath+“//maps//_zombiemode_wearms.gsc”);
int index=-1;//插入新行的位置。
列表换行符=新列表();
对于(int i=0;i-1)
{
换行。插入(索引,“测试21”);
}
string[]rebulidarr=newLines.ToArray();
试着这样做:
var newlines =
from line in File.ReadAllLines("source_filename.txt")
from newline in new []
{
line,
line.Contains("add_zombie_weapon") ? "test 21 " : null
}
where newline != null;
select newline;
File.WriteAllLines("destination_filename.txt", newlines);
看起来有一系列的
add\u zombie\u-wearm()
行,您想在该部分末尾添加一些内容吗
如果是这样,请尝试以下方法:
private void addgsc()
{
string file = modspath + "//maps//_zombiemode_weapons.gsc";
List<string> lines = new List<string>(System.IO.File.ReadAllLines(file));
int index = lines.FindLastIndex(item => item.Contains("add_zombie_weapon"));
if (index != -1)
{
lines.Insert(index + 1, "test 21");
}
System.IO.File.WriteAllLines(file, lines);
}
private void addgsc()
{
string file=modspath+“//maps//\u zombiemode\u warms.gsc”;
列表行=新列表(System.IO.File.ReadAllLines(文件));
int index=lines.findlastinex(item=>item.Contains(“添加僵尸武器”);
如果(索引!=-1)
{
行。插入(索引+1,“测试21”);
}
System.IO.File.writeAllines(文件,行);
}
你的问题是什么?这与OP的代码有不同的行为,OP的代码只插入一行“test 21”
——在最后一行包含“add\u zombie\u blast”
。如果多行包含该字符串,你的代码将添加多行“test 21”
行。@JimMischel-你说得对。我是,请原谅我的双关语,在OP的实际需求行之间阅读。