Jump to content


Check out our Community Blogs

Register and join over 40,000 other developers!


Recent Topics

Recent Status Updates

View All Updates

Photo
- - - - -

Read & Replace - .txt files


  • Please log in to reply
11 replies to this topic

#1 Sp32

Sp32

    CC Regular

  • Just Joined
  • PipPipPip
  • 26 posts

Posted 20 January 2011 - 06:45 AM

Hi, this task is very simple and I've found ways to do it other the internet (Strangely enough quite a lot of different ways; some ways for big files other ways for small files.)

My text files will be below 10mb, nothing too extensive.

Basically I have certain file I create from my server and I want to run a console application to search through it and delete several bits what are automatically inserted into the file.

[13:05:70] important text here what I want to keep - SQL Version 5.0
[13:05:70] important text here what I want to keep - SQL Version 5.0
[13:05:70] important text here what I want to keep - SQL Version 5.0
[13:05:70] important text here what I want to keep - SQL Version 5.0

I'd want to get rid of the red pieces of text from my .txt file, I have found code what does exactly what I want but the problem is I don't understand it and I don't want to be using code I don't understand, I've done a fair bit of studying on C# but I have just started attempting creating real useful applications instead of MessageBox.Show("loltext"); kind of things, so I'm a beginner but not absolute beginner, any help provided will be highly appreciated.

Thanks,

- Sp32

  • 0

#2 CommittedC0der

CommittedC0der

    CC Leader

  • Expert Member
  • PipPipPipPipPipPipPip
  • 1065 posts
  • Programming Language:C#
  • Learning:C#, JavaScript, PL/SQL

Posted 20 January 2011 - 01:02 PM

Well if you could post the code that's working we can try and walk you through how it works.

~ Committed. :)
  • 0
There IS a war going on for your mind.
Nothing of eternal significance happens besides prayer.

#3 Sp32

Sp32

    CC Regular

  • Just Joined
  • PipPipPip
  • 26 posts

Posted 20 January 2011 - 01:36 PM

All the parts in red are the parts I don't understand well, I know that they work but I don't know what they are actually doing

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main([COLOR=red][COLOR=black]string[] [/COLOR]args[/COLOR])
        {
            [COLOR=red]StringBuilder [/COLOR]newFile = new [COLOR=red]StringBuilder[/COLOR]();
            string temp = "";

            [COLOR=black]string[] file [/COLOR]= File.ReadAllLines(@"C:\Users\Bot\Desktop\work\test.txt");

            foreach (string line in file)
            {

                if (line.[COLOR=red]Contains[/COLOR]("Text What Needs Replacing"))
                {

                    temp = line.[COLOR=red]Replace[/COLOR]("Text What Needs Replacing", "Replacement Text");

[COLOR=red]                    newFile.Append(temp + "\r\n");[/COLOR]

                    [COLOR=black]continue;[/COLOR]

                }

                [COLOR=red]newFile.Append(line + "\r\n");[/COLOR]

            }

            [COLOR=red]File.WriteAllText[/COLOR](@"C:\Users\Bot\Desktop\work\test.txt", [COLOR=black]newFile[/COLOR].ToString());
        }
    }
}

  • 0

#4 CommittedC0der

CommittedC0der

    CC Leader

  • Expert Member
  • PipPipPipPipPipPipPip
  • 1065 posts
  • Programming Language:C#
  • Learning:C#, JavaScript, PL/SQL

Posted 20 January 2011 - 02:13 PM

Alright try reading this code.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main([COLOR=red][COLOR=black]string[] [/COLOR]args[/COLOR])
        {
            [COLOR=red]StringBuilder [/COLOR]newFile = new [COLOR=red]StringBuilder[/COLOR]();[COLOR=green]//StringBuilder is a built in class in C# That lets you construct large strings in a more efficient manner,[/COLOR] [COLOR=green]then just using a normal string.[/COLOR] [URL="http://www.switchonthecode.com/tutorials/csharp-snippet-tutorial-using-stringbuilder"]StringBuilder[/URL] [COLOR=green]<-- Nice Tutorial explaining it a little more clearly.[/COLOR]
            string temp = "";

            [COLOR=black]string[] file [/COLOR]= File.ReadAllLines(@"C:\Users\Bot\Desktop\work\test.txt");

            foreach (string line in file)
            {

                if (line.[COLOR=red]Contains[/COLOR]("Text What Needs Replacing"))[COLOR=green]//If 'line', which is obviously a line in the .txt file, contains "Text What Needs Replacing" continue, if not, goto the next 'line'.[/COLOR]
                {

                    temp = line.[COLOR=red]Replace[/COLOR]("Text What Needs Replacing", "Replacement Text");[COLOR=green]//This code works like this: line.Replace("text to replace", "text to replace with"); so it would change all occurrences of "text to replace" to "text to replace with".[/COLOR] 

[COLOR=red]                    newFile.Append(temp + "\r\n");[/COLOR][COLOR=green]//What '.Append' does is add a the given string(temp + \r\n) to a string which is newFile. BTW \r\n go's to the next line in the file.

                    [/COLOR][COLOR=black]continue;

                }

               [/COLOR][COLOR=black][COLOR=red]newFile.Append(line + "\r\n");[COLOR=green]//Same as before accept this time where adding 'line' to the string.[/COLOR][/COLOR]

            }

            [/COLOR][COLOR=black][COLOR=red]File.WriteAllText[/COLOR](@"C:\Users\Bot\Desktop\work\test.txt", [/COLOR][COLOR=black]newFile.ToString());[COLOR=green]//All File.WriteAllText does is writes a string(in this case newFile) to a given file.
    [COLOR=black]    }
    }
}


[/COLOR][/COLOR][/COLOR]
OK, well I hope this answered your questions, if you still dont understand just ask. ~ Committed. :)
  • 1
There IS a war going on for your mind.
Nothing of eternal significance happens besides prayer.

#5 Sp32

Sp32

    CC Regular

  • Just Joined
  • PipPipPip
  • 26 posts

Posted 20 January 2011 - 02:19 PM

Thanks a lot, that's helped me out quite a bit.

Personally I would have coded everything differently to how the coder coded it but I guess that's just something with new coders/personal preference.

I would also like to know how to arrange all lines in a text file alphabetically and how to remove all duplicates as well, if there is any sort of tutorial you can direct me to or explain yourself please do as I find it difficult finding tutorials by myself what suit my exact needs and I usually like a little bit of support
  • 0

#6 CommittedC0der

CommittedC0der

    CC Leader

  • Expert Member
  • PipPipPipPipPipPipPip
  • 1065 posts
  • Programming Language:C#
  • Learning:C#, JavaScript, PL/SQL

Posted 20 January 2011 - 02:42 PM

Well you can sort data stored in an array. So I suggest you read up on arrays, how to read .txt files into an array, and how to sort data in arrays. Here's some links:
My Array Tutorial: http://forum.codecal...ial-arrays.html
Still trying to find a nice tutorial on reading a .txt file into an array. :P
Sorting Arrays [C#]

Good Luck ~ Committed. :)
  • 1
There IS a war going on for your mind.
Nothing of eternal significance happens besides prayer.

#7 Sp32

Sp32

    CC Regular

  • Just Joined
  • PipPipPip
  • 26 posts

Posted 20 January 2011 - 06:17 PM

Thanks a lot mate, I really appreciate the help, I'll be reading up on those throughout the night, thank you!
  • 0

#8 Sp32

Sp32

    CC Regular

  • Just Joined
  • PipPipPip
  • 26 posts

Posted 21 January 2011 - 10:24 AM

I'm struggling again lol, basically I have a textbox, a menu strip and I want to have a button to automatically remove a bunch of occurences of x, the code I have the button to remove x text is:

        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            string tb = textBox1.Text;

            foreach (string line in tb)
            {

                if (line.Contains("Text What Needs Replacing"))
                {

                    tb = line.Replace("Text What Needs Replacing", "Replacement Text");

                    continue;

                }

            }
        }

but it keeps saying "Cannot implictly convert type 'char' to 'string'"

I tried changing using .ToString(); at the end of tb but that didn't seem to work either

  • 0

#9 CommittedC0der

CommittedC0der

    CC Leader

  • Expert Member
  • PipPipPipPipPipPipPip
  • 1065 posts
  • Programming Language:C#
  • Learning:C#, JavaScript, PL/SQL

Posted 21 January 2011 - 11:11 AM

Here try this:
string tb = textBox1.Text;
            string[] file = File.ReadAllLines(@"C:\Users\Bot\Desktop\work\test.txt");

            foreach (string line in file)[COLOR=green]//Where searching the file for occurrences of 'line' not tb.[/COLOR]
            {

                if (line.Contains("Text What Needs Replacing"))
                {
                    tb = line.Replace("Text What Needs Replacing", "Replacement Text");
                    continue;
                }

            }
EDIT: Are you trying to remove 'x' from the textbox? And not a file?
EDIT2: If you are you can just use this code:
textBox1.Text = textBox1.Text.Replace("replace this", "with this");

Hope this works. ~ Committed. :)
  • 1
There IS a war going on for your mind.
Nothing of eternal significance happens besides prayer.

#10 Sp32

Sp32

    CC Regular

  • Just Joined
  • PipPipPip
  • 26 posts

Posted 21 January 2011 - 04:04 PM

 textBox1.Text = textBox1.Text.Replace("replace this", "with this");
Is exactly what I was looking for! Thanks a lot.

If I had some text in my textbox such as:

[123randomgeneratedtexthere]
[123differentrandomgeneratedtexthere]
[123moredifferentautogeneratedtexthere]
How would I use:

textBox1.Text = textBox1.Text.Replace("replace this", "with this");
To remove all occurences of 123*? I assume there would be some sort of wildcard technique such as

textBox1.Text = textBox1.Text.Replace("[123*]", "");
But that doesn't work.

also is there a way to remove text inside placeholders, if I had a piece of text like:

("username: stephenson123")
To remove all occurences of ("and to delete whatever is inside of these?")
  • 0

#11 CommittedC0der

CommittedC0der

    CC Leader

  • Expert Member
  • PipPipPipPipPipPipPip
  • 1065 posts
  • Programming Language:C#
  • Learning:C#, JavaScript, PL/SQL

Posted 21 January 2011 - 04:34 PM

Whoa boy! Im pretty sure the only way to go about doing something like that is Regular expressions(Regex). Just to let you know Regex is NOT fun! This is what your code might look like to do what you stated above:
Regex rex = new Regex("123.*?\\ ");[COLOR=green]//See that "[COLOR=red].*?\\ [/COLOR]" ? Yeah thats regex, it finds '123' and searches until it finds a space.[/COLOR]
            int selectionStart = textBox1.SelectionStart;
            foreach (Match m in rex.Matches(textBox1.Text))
            {
                textBox1.Select(m.Index, m.Value.Length);
                textBox1.SelectedText = "New Text here";
                textBox1.Select(selectionStart, 0);
            }
I believe this is the Regex to pick up urls: (Got it offline so not sure if its exact)
[COLOR=blue]/[^="]http|ftp|gopher:\/\/[^ \n\r]+ (?=[\s\.,]) /
[/COLOR]
Not fun stuff.

~ Committed.
  • 1
There IS a war going on for your mind.
Nothing of eternal significance happens besides prayer.

#12 Sp32

Sp32

    CC Regular

  • Just Joined
  • PipPipPip
  • 26 posts

Posted 21 January 2011 - 04:50 PM

Dayum, strangely enough before you just posted I was reading a bit on regex and was thinking it's a lot to take in!

I'll start doing some studying on regex as I will need to use it in further projects what I have already planned on making (lol)

Thanks for all your help mate :-)
  • 0




Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download