现在尝试创建一些代码,从 CSV 文件中获取一个字符串并将其与某些条件进行比较。如果此字符串通过条件,则将其分为 4 部分 - 将每部分放入数组中,然后从 TextBox
中获取一些新值并进行更改。
目前,当需要分割选定的字符串时,我正处于正确的位置。准备一些代码,但不是获取分成几部分的数组,而是仅获取 System.string[]
代码
try
{
FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.ReadWrite);
StreamReader sr = new StreamReader(fs); //open file for reading
string[] line = sr.ReadToEnd().Split(new string[] { Environment.NewLine },
StringSplitOptions.None); //read file to the end an divide it
sr.Close(); //close stream
foreach (var l in line) //check each line for criteria
{
if (l.Contains(dateTimePicker1.Text.ToString() + eventNameUpdateTextBox.Text.ToString()))
{
try
{
string[] temp = { "", "", "", "", };// i always have just 4 part of string
for (int i = 0; i<3; i++)
{
updatedTtextBox.Text = temp[i] = l.Split(',').ToString(); //try to divide it
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
但结果 -
我哪里出错了?
最佳答案
调用l.Split(',')
会生成一个string
数组,即String[]
。对此类数组调用 ToString()
会生成 "System.String[]"
- 您在输出中看到的值。
您需要在循环之前进行拆分,并在索引中前进时从拆分中选择一个元素,然后对每个部分执行您需要执行的操作。如果您想要的只是将各个部分放入 temp
数组的各个元素中,也许将项目数量限制为 4
,则 l.Split(',' ).Take(4).ToArray()
应该足够了。
奇怪的是,在循环过程中,您替换了 updatedTtextBox.Text
四次。猜测一下您想要完成的任务,您可以尝试执行以下操作:
string[] temp = l.Split(',').Take(4).ToArray();
// For display purposes, you can join the data back with a different separator:
updatedTtextBox.Text = string.Join("|", temp);
关于c# - 如何: *. csv -->行-->someArray-->修改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18452684/