将行复制到新文件中,除了 c# 中文本文件中的特定行 [英] copy lines into new file except specific line from text file in c#

查看:21
本文介绍了将行复制到新文件中,除了 c# 中文本文件中的特定行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将数据从 textfile1 复制到新的文本文件 (textfile2).但是有一条我希望排除的特定行.我找到了一种方法来获取我想要排除的数据所在的行.

I'm trying to copy data from textfile1 to a new textfile (textfile2). but there's a specific line that i wish to exclude. i found a way to get the line where data i want to exclude is from.

我在这里做的是检查testfile.txt"是否存在.包含用户从 textbox1 输入的字符串.如果文件确实包含所述输入,则它会检查textfile1"中是否也有相同的输入.

What i'm doing here is that i'm checking if "testfile.txt" contains the string inputted by the user from textbox1. if the file does contain said input, it would then check if that same input is also available in "textfile1".

string old = @"textfile1.txt";
string new = @"textfile2.txt";
string test = @"testfile.txt";

string[] line = File.ReadAllLines(test);
for (int i = 0; i < line.Length; i++)
{
    if (line[i].Contains(textbox1.Text))
    {   
        string fileData = File.ReadAllText(path);
        for (int n = 0; n < line.Length; n++)
        {
            if (line[n].Contains(textbox1.Text))
            {
                n++; //gets line number
                
                //other code
            }
        }
    }
}

现在我想要做的是复制该 textfile1 中的所有内容,除了找到输入数据的行.

now what i want to do is to copy everything in that textfile1 except the line wherein the inputted data was found.

样本数据

textfile1.txt (id,item,price)

textfile1.txt (id,item,price)

0001,苹果,5

0002,香蕉,3

0003,芒果,6

用户在 textbox1 中输入 0002

假设输出

textfile2.txt

0001,苹果,5

0003,芒果,6

为什么不直接从文件中删除那一行?"好吧,我试过了,但是我也遇到了问题,所以我尝试这样做.

"why not just delete that line from the file?" well, i tried but yeah i'm having troubles with is too so i tried doing this instead.

我一直在尝试各种各样的事情,但我似乎无法做任何事情:(任何建议?任何形式的帮助将不胜感激!

I've been trying all sorts of things but i can't seem to make anything work :( any suggestions? any form of help would be appreciated!

推荐答案

你的循环太多了.你应该能够做到这一点:

You've got too many loops. You should be able to do it in one:

string oldFile = @"textfile1.txt";
string newFile = @"textfile2.txt";
string test = @"testfile.txt";

string[] lines = File.ReadAllLines(oldFile);

using (StreamWriter w = File.AppendText(newFile))
{
    foreach(var line in lines) {
        if (!line.Contains(textbox1.Text))
        {
            w.WriteLine(line);
        }
    }
}

或者,您也可以使用 LINQ 过滤掉不需要的行,然后一次性将它们全部写回:

Alternatively, you could also use LINQ to filter out the lines you don't want, and then write them back out all at once:

var newLines = File.ReadLines(oldFile).Where(l => !l.contains(textbox1.Text));
File.WriteAllLines(newFile, newLines);

这篇关于将行复制到新文件中,除了 c# 中文本文件中的特定行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆