-1

I would like to always delete two strings from my text file while reading it. DOC and PCB. so when ever these two strings is coming i would like to delete them and start my process. Please have a look to my output file https://imageshack.com/i/ipUcSIo2j i need the output file without these strings.

How can i do this. But i need my output Location column numbering should not vomit any numbers in between

My code snippet:

         string search_text = "PCB";
        string old;
        string n = "";
        StreamReader sr = File.OpenText(textBox1.Text);
        while ((old = sr.ReadLine()) != null)
        {
            if (!old.Contains(search_text))
            {
                n += old + Environment.NewLine;
            }
        }
        sr.Close();
        File.WriteAllText(textBox1.Text, n);
Stacy Kebler
  • 180
  • 1
  • 3
  • 22
  • 1
    Rather than reading in the whole file at once, read line by line and do what you need to during the read. – Jmoreland91 Nov 03 '14 at 16:27
  • @Jmoreland91 Okay is there any way,, i can do .. like before staring my entire process, can i delete pro-grammatically DOC and PCB from the text file.. and then start my process. i just need that can you help me out.. – Stacy Kebler Nov 03 '14 at 16:30
  • 1
    Sorry, too much code. Make your question - and the accompanying code - more specific. This will require work on your side to identify what the actual problem is, rather than just stating desired behaviour. Do you know _why_ your code isn't working? – Binary Worrier Nov 03 '14 at 16:31
  • 1
    What is "start the process"? – paparazzo Nov 03 '14 at 16:36
  • @BinaryWorrier Sorry about that, i am just trying to read a text file and then i am doing the above process. I mean removing the while spaces and aligning the text file and the saves it. SO what i need to do is before starting the above process i need to look for two rows.. that is DOC and PCB then delete this.. and save it..`System.IO.File.WriteAllText(textBox1.Text, sb.ToString());`. then i need to start the above coding process. – Stacy Kebler Nov 03 '14 at 16:37
  • @Blam start the process means... the above coding.. starts.. sorry about that!!! – Stacy Kebler Nov 03 '14 at 16:38
  • 2
    To delete the lines for the next file, you'll either have to do it on the way in or on the way out to the new file. You have to read it in to do it programmtically, you can use `while(file.Read())` or something similar to conditionally filter the lines out. – Jmoreland91 Nov 03 '14 at 16:44
  • 1
    So is your question "How do I remove two particular lines of text from a file"? – Binary Worrier Nov 03 '14 at 18:12
  • @BinaryWorrier yes.. i am now able to delete the entire line that contains word "PCB".. i need to delete the word DOC too from the text file – Stacy Kebler Nov 03 '14 at 18:15
  • Possible duplicate of http://stackoverflow.com/questions/532217/efficient-way-to-delete-a-line-from-a-text-file – Binary Worrier Nov 03 '14 at 18:18
  • @BinaryWorrier Yes i saw the post but its not helpful for me.. I just need to delete two words from my text file.. I have already uploaded the code to delete the word `PCB` from my textfile. I just need to delete DOC from this text file.. can you help me please – Stacy Kebler Nov 03 '14 at 18:21

4 Answers4

1

Firstly, see this question and it's accepted answer Efficient way to delete a line from a text file

So you need to do that, read through the file, writing the lines you want to a new file, and skipping the lines you don't want. There actually is NO way to delete lines from a text file, and this is how you fake the delete.

Then run your code on the new file.

Do you need help identifying the lines to remove, or are you OK with that?

Community
  • 1
  • 1
Binary Worrier
  • 50,774
  • 20
  • 136
  • 184
  • You -1 me and then post an answer that is nothing but a link to a duplicate you already flagged as a duplicate and OP said he did not understand. – paparazzo Nov 03 '14 at 18:29
  • Yes i need to identify... the line with DOC.. i have already identified PCB and and deleted it.. I just need to do for DOC. i mean how can i do in an array structure// – Stacy Kebler Nov 03 '14 at 18:30
  • @Blam: If you don't like my answer feel free to vote it down, or edit it to make it better. I'm sorry dude, but you don't actually answer the question. If you change your answer so it attempts to answer the question I'll remove the down vote, if you change it so it actually answers the question well I'll vote it up. – Binary Worrier Nov 04 '14 at 08:29
  • If you check the comment history I made attempt to determine what he was asking. And it seemed he was asking how to run code when the program started. That question has been through a lot of editing. – paparazzo Nov 04 '14 at 13:22
1

I think it should be simple like this.

string[] search = new string[] {"DOC","PCB"};
var lines = System.IO.File.ReadAllLines(@"D:\MyFile.txt");
var result1 = lines.Where(item => !item.Contains(search[0]) && !item.Contains(search[1]));
StringBuilder sb = new StringBuilder();
foreach (string line in result1)
{
    sb.AppendLine(line);
}
Shell
  • 6,818
  • 11
  • 39
  • 70
0

i got the answer..For deleting two word plus entire line i used two different functions, where each function servers a different role. Please have a look to my answer. I know that this is bit lengthy and it can be done suing an array system. If any better answers are posted i am ready to accept it.

 public void do_name()
    {
        string search_text = "PCB";
        string old;
        string n = "";
        StreamReader sr = File.OpenText(textBox1.Text);
        while ((old = sr.ReadLine()) != null)
        {
            if (!old.Contains(search_text))// || !old.Contains(next_text)) 
            {
                n += old + Environment.NewLine;
            }
        }
        sr.Close();
        File.WriteAllText(textBox1.Text, n);
    }

    public void do_name1()
    {
        string next_text = "DOC";
        string old;
        string n = "";
        StreamReader sr = File.OpenText(textBox1.Text);
        while ((old = sr.ReadLine()) != null)
        {
            if (!old.Contains(next_text))// || !old.Contains(next_text)) 
            {
                n += old + Environment.NewLine;
            }
        }
        sr.Close();
        File.WriteAllText(textBox1.Text, n);
    }
    Dictionary<string, int> namesForCarousels = new Dictionary<string, int>();
    private void button1_Click(object sender, EventArgs e)
    {
        string path = "";
        string filename_noext = "";
        OpenFileDialog ofd = new OpenFileDialog();
        ofd.InitialDirectory = @"C:\files";
        ofd.Filter = "TXT files (*.txt)|*.txt";
        ofd.FilterIndex = 2;
        ofd.RestoreDirectory = true;

        if (ofd.ShowDialog() == DialogResult.OK)
        {
            filename_noext = System.IO.Path.GetFileName(ofd.FileName);
            path = Path.GetFullPath(ofd.FileName);
            textBox1.Text = path;
            do_name();
            do_name1();
            //MessageBox.Show(filename_noext, "Filename"); - - -> switching.grf
            //MessageBox.Show(path, "path");
            //Give the column width according to column index.
            int[] cols = new int[] { 15, 15, 25, 15, 15 };
            string[] strLines = System.IO.File.ReadAllLines(textBox1.Text);

            StringBuilder sb = new StringBuilder();
            string line = string.Empty;
            string LastComment = string.Empty;
            string CarouselName = "Carousel";
            int iCarousel = 0;

            for (int i = 0; i < strLines.Length; i++)
            {

                line = RemoveWhiteSpace(strLines[i]).Trim();
                string[] cells = line.Replace("\"", "").Split('\t');

                for (int c = 0; c < cells.Length; c++)
                    sb.Append(cells[c].Replace(" ", "_").PadRight(cols[c]));

                if (cells.Length > 1)
                {
                    var name = cells[1];
                    int carouselNumber;
                    if (namesForCarousels.TryGetValue(name, out carouselNumber) == false)
                    {
                        carouselNumber = iCarousel++;
                        namesForCarousels[name] = carouselNumber;
                    }
                    if (i == 0)
                        sb.Append("Location".PadRight(15));
                    else
                        sb.Append(String.Format("{0}:{1}", CarouselName, carouselNumber).PadRight(15));
                }
                sb.Append("\r\n");
            }

            System.IO.File.WriteAllText(textBox1.Text, sb.ToString());
           // do_name1();
            Application.Exit();
        }
    }
Stacy Kebler
  • 180
  • 1
  • 3
  • 22
  • you could combine the two `do_` methods, they only differ with the search term. So if you made the inner `if` an AND: `if (!old.Contains("DOC") && !old.Contains("PCB"))` – cjb110 Nov 04 '14 at 07:58
-1

Just put that code in the ctor/constructor under InitializeComponent();

paparazzo
  • 44,497
  • 23
  • 105
  • 176