Click here to Skip to main content
14,669,324 members
Rate this:
Please Sign up or sign in to vote.
See more:
I need to search the words in a log file like "INFO", "ERROR", "WARN" "FATAL" in a file and need to replace it to the word "DEBUG" on the check box click. If I uncheck the box, the words from "DEBUG" should replaced to the original state like "INFO", "ERROR" e.t.c.


I am not sure how to handle it Array or something. Also, how to hold the previous state of the file?

private void ToggleforDebugMode(bool IsDebug)
    {
        string text = @"C:\Program Files (x86)\Hi.config";
        string filePath = Path.GetDirectoryName("Hi.config") + fileName;
        text = File.ReadAllText(@"C:\Program Files (x86)\Hi.config");
        if (IsDebug)
        {
            _previousState = text.Contains("WARN") ? "WARN" : "INFO";

            if(text.Contains("WARN"))
            {
                text = text.Replace("WARN", "DEBUG");
            }
            else if (text.Contains("DEBUG"))
            {
                text = text.Replace("INFO", "DEBUG");
            }               

        }
        else
        {
             text = text.Replace("DEBUG", _previousState);
        }
        File.WriteAllText(@"C:\Program Files (x86)\Galileo Print Manager .NET\GPM_Service.exe.config", text);
    }


What I have tried:

I tried to use File.Replace() method. But it is helpful for searching & replacing only one word.
Posted
Updated 27-Apr-18 20:12pm
v2

1 solution

Rate this:
Please Sign up or sign in to vote.

Solution 1

What comes to replacing the words, why not simply use multiple Replace operations. For example
...
text = text.Replace("INFO", "DEBUG");
text = text.Replace("ERROR", "DEBUG");
text = text.Replace("WARN", "DEBUG");
...


And that comes to the previous state, probably the easiest way is to re-read the file to the variable.
   
Comments
Member 13498963 28-Apr-18 3:30am
   
Yeah thanks for this. but I am struggling to make a loop for this scenario like to "how to find the WARN & DEBUG available in the text file?"
Wendelius 28-Apr-18 4:42am
   
What do you want to loop? Do you have multiple text files, or something else?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100