如何更新CSV文件中的行?

szqfcxe2  于 2023-01-10  发布在  其他
关注(0)|答案(3)|浏览(146)

我正在尝试更新文件中字符串的某个部分。目前我的代码是:

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());

不改变字符串并返回与开头相同的字符串。为什么会发生这种情况?我错在哪里了?

23c0lvtd

23c0lvtd1#

字符串是不可变的,这意味着它们不能改变。你需要创建一个新的字符串并将其赋给变量。

l = l.Remove(start, eventName.Length);
l = l.Insert(start, newNameTextBox.Text.ToString());

MSDN
字符串是不可变的--字符串对象的内容在对象创建后不能更改,尽管语法使它看起来好像您可以这样做。
Why .NET String is immutable?

kognpnkq

kognpnkq2#

你必须将这些改变赋给一个新的(字符串)变量。这个字符串变量不能是l,因为它是在foreach loop中迭代的变量,因此不能被改变。你必须依赖一个临时变量,如下面的代码所示。

foreach (var l in line)
{
    if (l.Contains(eventName))
    {
        string temp = l;
        int start = l.IndexOf(eventName);
        temp = temp.Remove(start, eventName.Length);
        temp = temp.Insert(start, newNameTextBox.Text.ToString());
        lines.Add(temp);
    }
    else
    {
        lines.Add(l);
    }
}
ewm0tg9j

ewm0tg9j3#

字符串上的函数返回结果字符串,但不更改字符串的值(如果不是全部,也是大部分字符串)
试试这个:

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 = l.Remove(start, eventName.Length);
            l = l.Insert(start, newNameTextBox.Text.ToString());
            lines.Add(l);
        }
        else
        {
            lines.Add(l);
        }   
    }
    string toCsvOutput = string.Join(Environment.NewLine, lines.ToArray());

相关问题