Writing to a text file using StremWriter

Ask general questions here.
Jenny
Posts: 18
Joined: Thu Apr 14, 2016 5:04 pm

Writing to a text file using StremWriter

Post by Jenny » Fri Apr 29, 2016 5:12 pm

Hi,

I have an csv file attached to my script and one of the columns in the file is YEAR. I use 'vehYear' as variable to bind to 'YEAR' column. I want to create a file called TestResult.txt and write the content of the variable 'vehYear' to the TestResult.txt using StreamWriter.WriteLine.Somehow I cannot get the value of the variable written to the TestResult.txt file. I debugged it, and y is getting the correct value in the Writeline line...but TestResult.txt doesn't seem to get printed the value of y. It prints only the string
"Answer is "

This is my code:

using (StreamWriter myWriter = new StreamWriter("C:\\...\\testresult.txt",true))
{
string y = year.ToString();
result = " Answer is ";
myWriter.WriteLine(result, y);
}

my Output in TestResult.txt file is :- Answer is

Thanks for any help,
Jenny

krstcs
Ranorex Guru
Posts: 2683
Joined: Tue Feb 07, 2012 4:14 pm
Location: Austin, Texas, USA

Re: Writing to a text file using StremWriter

Post by krstcs » Fri Apr 29, 2016 7:25 pm

Try this:

Code: Select all

myWriter.WriteLine(result + y); 
Or, if you want to use the formatted version do this:

Code: Select all

result = "Answer is {0}";  
myWriter.WriteLine(result, y); 
Formatted statements require place-holders in the form "{<index>}", where index is a 0-based index of the list of objects following the format string in the method. In this case, y is the 0th value in the list of values after the format string 'result'.
Shortcuts usually aren't...

Jenny
Posts: 18
Joined: Thu Apr 14, 2016 5:04 pm

Re: Writing to a text file using StremWriter

Post by Jenny » Fri Apr 29, 2016 10:14 pm

Hi,

Somehow it didn't work with Writeline..But it did work with
myWriter.Writer(result +y);

Thanks!

Jenny
Posts: 18
Joined: Thu Apr 14, 2016 5:04 pm

Re: Writing to a text file using StremWriter

Post by Jenny » Fri Apr 29, 2016 10:15 pm

I mean

myWriter.Write(result +y);

krstcs
Ranorex Guru
Posts: 2683
Joined: Tue Feb 07, 2012 4:14 pm
Location: Austin, Texas, USA

Re: Writing to a text file using StremWriter

Post by krstcs » Mon May 02, 2016 2:55 pm

Hmm... It should work with either one, they do the same thing except for the end-of-line characters.

Write puts the given string into the current cursor location, without adding the end-of-line characters.

WriteLine puts the given string into the current cursor location AND adds the end-of-line characters.

Anyway, glad it helped.
Shortcuts usually aren't...