有一个文件(E:\sample.txt
),如下所示:
Indian
English
Spanish
French
English
Spanish
English
Polish
French
现在我想编写一个Windows应用程序(C#语言)来搜索该文件中的单词English
并删除该行(如果存在)。如果不退出,则会向not found
的用户发送消息。
正如您所看到的那样,可能有多行包含单词English
,我想删除所有这些行并使该行“#”;#39; NULL'。
答案 0 :(得分:0)
您无法真正删除文件中的行。你需要做的是用一个没有不需要的行的新文件用不需要的行覆盖文件
static void DeleteLines(string filename, string searchText) {
bool searchTextFound = false;
// Obtain the filtered lines
var filteredLines = File.ReadLines(filename).Where(line => !(searchTextFound = line.Contains(searchText)) /* You can use case insensitive match, regex matching, etc here */ );
if (searchTextFound) {
// Create a temp file to store the filtered lines. You can do it in memory, if you know that the file is small
string destFilename = Path.GetTempFileName();
File.WriteAllLines(destFilename, filteredLines);
// Now overwrite the original file with the filtered lines
File.Delete(filename);
File.Move(destFilename, filename);
} else {
Console.WriteLine($"Search Text '{searchText}' not found");
}
}
static void Main(string[] args) {
DeleteLines("Test.txt", "English");
}
答案 1 :(得分:0)
using System;
using System.IO;
public static class FileHelper {
public static int RemoveLines(string path, Predicate<string> remove) {
var removed = 0;
var lines = File.ReadAllLines(path);
using (var output = new StreamWriter(path)) {
foreach (var line in lines) {
if (remove(line)) {
removed++;
} else {
output.WriteLine(line);
}
}
}
return removed;
}
}
RemoveLines函数通过“删除”特定行来重写文件,并返回“已删除”行的数量。在您的情况下,您可以使用:
if (FileHelper.RemoveLines("E:\\sample.txt", (l) => { return l = "English"; }) == 0)
Console.WriteLine("not found.");
答案 2 :(得分:0)
这是winform
。 textbox1
是您输入单词的地方,textbox2
将显示该消息。
textBox2.Clear();
if (!string.IsNullOrWhiteSpace(textBox1.Text))
{
string LinesToDelete = textBox1.Text;
var Lines = File.ReadAllLines(@"E:\sample.txt");
if (Lines.Contains(textBox1.Text))
{
var newLines = Lines.Where(line => !line.Contains(LinesToDelete));
File.WriteAllLines(@"E:\sample.txt", newLines);
textBox2.Text = "Removed";
}
else
{
textBox2.Text = "Not found";
}
}
如果您不需要显示消息,则下面的代码就足够了。
var Lines = File.ReadAllLines(@"E:\sample.txt");
var newLines = Lines.Where(line => !line.Contains(LinesToDelete));
File.WriteAllLines(@"E:\sample.txt", newLines);