1

如果我只知道部分字符串代码,请尝试从 csv 文件中删除一些条目

 //open File
        FileStream fs = new FileStream(filePath, FileMode.Open, 
            FileAccess.ReadWrite);
        StreamReader sr = new StreamReader(fs);            
 //divide file entry for separate lines
        string []line = sr.ReadToEnd().Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
 // find required entry and create new List without it
        List<string> finalData = new List<string>();
        foreach (var l in line)
        {
            if (!line.Contains((dateTimePicker1.Text.ToString().Trim() + ','+ eventNameDeleteTextBox.Text.ToString().Trim()+',')))
                finalData.Add(l);
        }
  // convert to array
        string toCsvoutput = string.Join(Environment.NewLine, finalData.ToArray());
      //  viewTextBox1.Text=toCsvoutput; 

        //updateFile
        sr.Close();
        FileStream fs1 = new FileStream(filePath, FileMode.Open,FileAccess.Write, FileShare.None);
        StreamWriter sw = new StreamWriter(fs1);
        sw.WriteLine(toCsvoutput);
        sw.Close();

结果 - 什么都没发生,我错在哪里?

4

3 回答 3

2

用 l 替换行:

  if (!l.Contains((dateTimePicker1.Text.ToString().Trim() + ','+ 
    eventNameDeleteTextBox.Text.ToString().Trim()+',')))
     finalData.Add(l);
于 2013-08-26T09:07:10.977 回答
1

你可以清理很多:

string skipText = (dateTimePicker1.Text.ToString().Trim() + ','+
      eventNameDeleteTextBox.Text.ToString().Trim()+',')

var linesIn = System.IO.File.ReadLines(filePath);
var linesOut = linesIn.Where(line => ! line.Contains(skipText));
linesOut = linesOut.ToList();  // make sure the file is closed again
System.IO.File.WriteAllLines(filePath, linesOut);
于 2013-08-26T09:14:17.583 回答
0

foreach语句中的条件可能总是通过。你应该使用调试来检查条件本身,确保它是你的。

另外,你应该做

string condition = dateTimePicker1.Text.ToString().Trim() + ','+ eventNameDeleteTextBox.Text.ToString().Trim()+',';

foreach声明之外,所以你不会白白浪费时间。

于 2013-08-26T09:05:12.443 回答