大家都尝试在某些csv文件中删除行; 文件示例:
24 august 2013 г.,,14:00,00:00,;
24 august 2013 г.,,14:00,00:00,;
24 august 2013 г.,2342,14:00,00:00,23424;
24 august 2013 г.,2342,14:00,19:00,23424;
criteria - 24 august 2013 г.,2342
结果必须像
24 august 2013 г.,,14:00,00:00,;
24 august 2013 г.,,14:00,00:00,;
我的想法
打开文件 -
FileStream fs = new FileStream(filePath, FileMode.Open,
FileAccess.ReadWrite);
StreamReader sr = new StreamReader(fs);
将所有数据输入到数组
string lines = sr.ReadToEnd();
string []result = lines.Split(';');
获取删除数据的标准(某些字符串)
string criteria = dateTimePicker1.Text.ToString()+','
+eventNameDeleteTextBox.Text.ToString();
sr.Close();
在数组中搜索,
int startStr = lines.IndexOf(criteria);//find start position
int length = lines.IndexOf(';',startStr)-startStr;//find end position
删除 string dataRemoved = lines.Substring(startStr,length); viewTextBox.Text = dataRemoved;
并写入文件更新数据
FileStream fs1 = new FileStream(filePath, FileMode.Open,
FileAccess.Write, FileShare.None);
StreamWriter sw = new StreamWriter(fs1);
sw.WriteLine(dataRemoved);
sw.Close();
但它的工作不正确 - 它;必须删除到文件开头的复制字符串并删除所有;符号,哪里错了?
答案 0 :(得分:1)
尝试这样的事情,如果你的文件很小,那么下面的解决方案应该不是问题。
string rawdata = @"24 august 2013 г.,,14:00,00:00,;
24 august 2013 г.,,14:00,00:00,;
24 august 2013 г.,2342,14:00,00:00,23424;
24 august 2013 г.,2342,14:00,19:00,23424;";//consider this is raw file
string[] lines = rawdata.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
List<string> result = new List<string>();
foreach (var line in lines)
{
if (!line.Contains("24 august 2013 г.,2342"))
{
result.Add(line);
}
}
现在您的预期结果将在result
列表中。您可以使用结果列表创建新文件。
如果没有回答您的问题,请提供更多信息。我会尝试提供更好的解决方案。