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
Avatar of Chinmay Patel
Chinmay Patel
Flag of India image

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
Avatar of Chinmay Patel
Chinmay Patel
Flag of India image

Blurred text
THIS SOLUTION IS 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
Avatar of Isabell
Isabell

ASKER

Thanks Chinmay,
That was a perfect solution!
Avatar of Chinmay Patel
Chinmay Patel
Flag of India image

Glad I could help.
.NET Programming
.NET Programming

The .NET Framework is not specific to any one programming language; rather, it includes a library of functions that allows developers to rapidly build applications. Several supported languages include C#, VB.NET, C++ or ASP.NET.

137K
Questions
--
Followers
--
Top Experts
Get a personalized solution from industry experts
Ask the experts
Read over 600 more reviews

TRUSTED BY

IBM logoIntel logoMicrosoft logoUbisoft logoSAP logo
Qualcomm logoCitrix Systems logoWorkday logoErnst & Young logo
High performer badgeUsers love us badge
LinkedIn logoFacebook logoX logoInstagram logoTikTok logoYouTube logo