1

如果第一个单词与我拥有的变量匹配,如何从文本文件中删除整行?

我目前正在尝试的是:

List<string> lineList = File.ReadAllLines(dir + "textFile.txt").ToList();
lineList = lineList.Where(x => x.IndexOf(user) <= 0).ToList();
File.WriteAllLines(dir + "textFile.txt", lineList.ToArray());

但我无法将其删除。

4

4 回答 4

2

您唯一的错误是使用 indexOf 检查 <= 0,而不是 = 0。

当字符串不包含搜索字符串时返回-1。

<= 0 表示以或不包含开头

=0 表示以 <- 开头,这就是你想要的

于 2012-05-18T18:01:35.413 回答
1

此方法将逐行读取文件,而不是一次全部读取。另请注意,此实现区分大小写。

它还假设您不受前导空格的影响。

using (var writer = new StreamWriter("temp.file"))
{
    //here I only write back what doesn't match
    foreach(var line in File.ReadLines("file").Where(x => !x.StartsWith(user)))
        writer.WriteLine(line);  // not sure if this will cause a double-space ?
}

File.Move("temp.file", "file");
于 2012-05-18T17:49:31.240 回答
1

你非常接近,String.StartsWith处理得很好:

// nb: if you are case SENSITIVE remove the second argument to ll.StartsWith
File.WriteAllLines(
    path,
    File.ReadAllLines(path)
        .Where(ll => ll.StartsWith(user, StringComparison.OrdinalIgnoreCase)));

对于可能性能不佳的非常大的文件,请改为:

// Write our new data to a temp file and read the old file On The Fly
var temp = Path.GetTempFileName();
try
{
    File.WriteAllLines(
        temp,
        File.ReadLines(path)
            .Where(
               ll => ll.StartsWith(user, StringComparison.OrdinalIgnoreCase)));
    File.Copy(temp, path, true);
}
finally
{
    File.Delete(temp);
}

另一个需要注意的问题是,如果用户是,则IndexOfandStartsWith都会将ABCandABCDEF视为匹配项ABC

var matcher = new Regex(
    @"^" + Regex.Escape(user) + @"\b", // <-- matches the first "word"
    RegexOptions.CaseInsensitive);
File.WriteAllLines(
    path,
    File.ReadAllLines(path)
        .Where(ll => matcher.IsMatch(ll)));
于 2012-05-18T17:57:34.363 回答
0
Use  `= 0` instead of `<= 0`. 
于 2012-05-18T17:48:30.367 回答