0

I’m looking for a way to search through my cs file and replace some text with the name of the local function.

e.g.

private void SampleFunction()
{
  string foo = “bar“;
}

Task: search for each „bar“ and replace with function name.

Result would be:

private void SampleFunction()
{
  string foo = “SampleFunction“;
}

I’m aware I could use reflection during runtime, but the functions name are unreadable due to obfuscation, that’s why I like to put the function name into a string. Automated for 600 functions I use.

Is there any (easy) way to archive this? Thank you for your support.

Btw. I googled and searched through stack Overflow but did not found any helpful post for this particular case.

Butti
  • 359
  • 2
  • 6

2 Answers2

0

If you just want to do this in VS, you can do a ctrl-shift-H to find and replace. This can be done in a file, a folder, a project, or a solution.

If you want to do it in code, you can use something like this

How to Find And Replace Text In A File With C#

0

As the other answerer said, you can use Ctrl+Shift+H to search and replace across all files, but you'll need some fairly clever regex (regular expressions) to get what you want directly. You would have to set the search-replace to use regular expressions using the checkbox for that. (Don't forget to turn it off afterward if you don't use it regularly.)

In your example, it would be simple to look for

void (\S+)\(\)(\s*){(\r\n\s*)string foo = "bar";

and replace it with something like

void $1()$2{$3string foo = "$1";

Or rather it would be simple if you already know regex. I tried this regex on some of my own code and it worked. However, it gets a lot harder if some methods take parameters and others don't, if some are void and others return something, if visibility keywords like public and private both appear, etc., etc.

So honestly you may just want to bite the bullet and do these in part by hand. You could do searching for signature characteristics (like void or public) and hand-edit each instance.

You could also write code that works over your files, but that would certainly take much longer than other options.

BTW there's a function called nameof(…) that also does this nicely — but you'd still have to identify every place to use it, and it returns runtime values when used, so if names are obfuscated, nameof()'s also should be.

If you search the web for regular expressions for this purpose, you may find something advanced enough to fully suit your search needs. Editing it to do exactly what you need will be a bear unless you know regex or have the time to learn it right now. :-)

Hope this helps!