Click here to Skip to main content
15,889,281 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
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?

C#
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

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.
 
Share this answer
 
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, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900