We help IT Professionals succeed at work.

How can I replace a string in a file?

Isabell
Isabell asked
on
145 Views
Last Modified: 2018-11-08
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

Chinmay PatelChief Technology Ninja
CERTIFIED EXPERT
Distinguished Expert 2019

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
CERTIFIED EXPERT
Distinguished Expert 2019
Commented:
This problem has been solved!
(Unlock this solution with a 7-day Free Trial)
UNLOCK SOLUTION

Author

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

Commented:
Glad I could help.