How can I replace a string in a file?

Isabell
Isabell used Ask the Experts™
on
Hi,
I have a batch file as below:
call "C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\Common7\Tools\VsDevCmd.bat"
cd C:\AutomationTestSamples\AutomationTestSamples\bin\Debug
start cmd /k vstest.console.exe AutomationTestSamples.dll /Logger:trx;LogFileName=%1/UnitTest1.trx /testcasefilter:FullyQualifiedName~AutomationTestSamples.UnitTest1.trx

Open in new window


I want to read a batch file line by line and if the line contains "UnitTest1.trx",
I want to replace "/testcasefilter:FullyQualifiedName~AutomationTestSamples.UnitTest1" with "/test".

I tried the following code but when I opened the file nothing was replaced.  Any idea please?
string[] str = File.ReadAllLines(@"C:\Test\test.bat");
            for (int i = 0; i < str.Length; i++)
            {
                if (str[i].Contains(trxName))
                {
                    str[i].Replace(str[i].Substring(str[i].IndexOf("/testcasefilter")), "/test");                    
                }
                
            }

Open in new window

Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Chinmay PatelChief Technology Ninja
Distinguished Expert 2018

Commented:
Hi Isabell,

In the code sample above you are just reading the file contents in an string array. You need to write back those lines to the file as well to get the desired results.

Also string.Replace https://docs.microsoft.com/en-us/dotnet/api/system.string.replace?redirectedfrom=MSDN&view=netframework-4.7.2#System_String_Replace_System_String_System_String_ returns a string value which you have to use. It does not actually replace/change the content of the string.

Regards,
Chinmay.
Chief Technology Ninja
Distinguished Expert 2018
Commented:
So
str[i].Replace(str[i].Substring(str[i].IndexOf("/testcasefilter")), "/test");                    

Open in new window


should be
str[i] = str[i].Replace(str[i].Substring(str[i].IndexOf("/testcasefilter")), "/test");                    

Open in new window


And after your For loop has ended, use File.WriteAllLines method https://docs.microsoft.com/en-us/dotnet/api/system.io.file.writealllines?view=netframework-4.7.2

For example,
File.WriteAllLines(@"C:\Test\test.bat", str);

Open in new window

Author

Commented:
Thanks Chinmay,
That was a perfect solution!
Chinmay PatelChief Technology Ninja
Distinguished Expert 2018

Commented:
Glad I could help.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial