我正在尝试更新文件中字符串的某个部分。目前我的代码是:
FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
StreamReader sr = new StreamReader(filePath);
string[] line = sr.ReadToEnd().Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
List<string> lines = new List<string>();
string eventName = ','+eventNameUpdateTextBox.Text.ToString()+',';
foreach (var l in line)
{
if (l.Contains(eventName))
{
int start = l.IndexOf(eventName);
l.Remove(start, eventName.Length);
l.Insert(start, newNameTextBox.Text.ToString());
lines.Add(l);
}
else
{
lines.Add(l);
}
}
string toCsvOutput = string.Join(Environment.NewLine, lines.ToArray());
但我得到的结果是和以前一样的文件。
当我试着调试它时,我看到了这个函数:
l.Insert(start, newNameTextBox.Text.ToString());
不改变字符串并返回与开头相同的字符串。为什么会发生这种情况?我错在哪里了?
3条答案
按热度按时间23c0lvtd1#
字符串是不可变的,这意味着它们不能改变。你需要创建一个新的字符串并将其赋给变量。
MSDN:
字符串是不可变的--字符串对象的内容在对象创建后不能更改,尽管语法使它看起来好像您可以这样做。
Why .NET String is immutable?
kognpnkq2#
你必须将这些改变赋给一个新的(字符串)变量。这个字符串变量不能是
l
,因为它是在foreach loop
中迭代的变量,因此不能被改变。你必须依赖一个临时变量,如下面的代码所示。ewm0tg9j3#
字符串上的函数返回结果字符串,但不更改字符串的值(如果不是全部,也是大部分字符串)
试试这个: