Avatar of Isabell
Isabell
 asked on

How can I replace a string in a file?

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

.NET ProgrammingC#

Avatar of undefined
Last Comment
Chinmay Patel

8/22/2022 - Mon
Chinmay Patel

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.
ASKER CERTIFIED SOLUTION
Chinmay Patel

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
Isabell

ASKER
Thanks Chinmay,
That was a perfect solution!
Chinmay Patel

Glad I could help.
All of life is about relationships, and EE has made a viirtual community a real community. It lifts everyone's boat
William Peck