C# 更改文本文件中的行
我的文本文档包含行名和下一行的值。 这是我写的,但在替换后我无法重写这行C# 更改文本文件中的行,c#,winforms,C#,Winforms,我的文本文档包含行名和下一行的值。 这是我写的,但在替换后我无法重写这行 public bool checkExist(string catName) { int saveValue = 0; bool found = false; foreach (string line in File.ReadLines(Form1.INCOMES_EXPENSE_VALUES_MONTH + Form1.CurrentMonth.ToString() + ".t
public bool checkExist(string catName)
{
int saveValue = 0;
bool found = false;
foreach (string line in File.ReadLines(Form1.INCOMES_EXPENSE_VALUES_MONTH + Form1.CurrentMonth.ToString() + ".txt"/*get the file that I need to search in*/))
{
if (line == catName)
{
found = true;
index++;
continue;
}
else
index++;
if (found)
{
saveValue = int.Parse(line);
saveValue += int.Parse(txtValue.Text);
line.Replace(line, saveValue.ToString());
found = false;
return true;
}
}
return false;
}
我建议实现一个简单的有限状态机;这里有两种状态:前面的行是
catName
(found==true
)或不是(found==false
):
事实上,您只能通过回写整个文件(行)来修改文件(行), 例如:
读取整个文件行
修改temp中的行
将修改后的整行写回文件
要更改文件中的行
ChangeLine(@"This is modified line", @"C:\MyFile.txt", 6);
DeleteLine(@"C:\MyFile.txt", 6);
要删除文件中的行
ChangeLine(@"This is modified line", @"C:\MyFile.txt", 6);
DeleteLine(@"C:\MyFile.txt", 6);
在文件的行索引处插入行
InsertLineAtIndex(@"C:\MyFile.txt", 6, @"This is new line");
通过文件中的已知字符串插入行
InsertLineByKnownString(@"C:\MyFile.txt", "Some string in my lines", @"This is new line ");
您需要将文件写回磁盘,您可以查找examples@styx,如果输入字符串已存在于文件中,则我需要将其值添加到旧字符串中,然后使用新值替换该行,该操作正常,但我无法使用新值更改文件中的行为什么不能更改?@styx,对不起,我的意思是不知道如何在文件中更改它如果你正在读取所有行,你可以截断文件,然后写新行只是一个离题的建议:不要假设OP使用的是最新的C#编译器;您引入了字符串插值(需要C#6),其中OP使用
ToString
和一个简单的连接。您确实提供了对OP无法意识到的有价值技术的洞察,但与此同时,由于与原始代码示例的其他差异,解决方案的复杂性正在增加。
InsertLineAtIndex(@"C:\MyFile.txt", 6, @"This is new line");
public static void InsertLineAtIndex(
string fullPath,
int atIndex,
string lineToAdd,
bool toBelow = false)
{
// Read entire file lines
var txtLines = File.ReadAllLines(fullPath).ToList();
// Specify insert location
int index = toBelow ? (atIndex - 1) + 1 : (atIndex - 1);
if (index > 0)
{
// Insert the line
txtLines.Insert(index, lineToAdd);
// Write back to file
File.WriteAllLines(fullPath, txtLines, Encoding.UTF8);
}
}
InsertLineByKnownString(@"C:\MyFile.txt", "Some string in my lines", @"This is new line ");
public void InsertLineByKnownString(
string fullPath,
string lineToSearch,
string lineToAdd,
bool toBelow = false)
{
// Read entire file lines
var txtLines = File.ReadAllLines(fullPath).ToList();
// Specify insert location
int index = toBelow ? txtLines.IndexOf(lineToSearch) + 1 : txtLines.IndexOf(lineToSearch);
if (index > 0)
{
// Insert the line
txtLines.Insert(index, lineToAdd);
// Write back to file
File.WriteAllLines(fullPath, txtLines, Encoding.UTF8);
}
}