views:

55

answers:

3

How to make web service methods return string value in lines format?

My web service method looks like this

[WebMethod]
public string GetSomeLines()
{
  System.Text.StringBuilder builder = new StringBuilder();
  builder.AppendLine("Line1.");
  builder.AppendLine("Line2.");
  builder.AppendLine("Line3.");
  return builder.ToString();
}

But when I get the result from web browser or from delphi/c# consumer it will be like this:

Line1. Line2. Line3.

While I expect to see:

Line1.
Line2.
Line3.

I know may be returning a StringBuilder or String Array is an option here but I want to know if there is a way to make this with string result.

Thanks for your help.

+1  A: 

you can add the '\r\n' character at the end of each append:

builder.Append("Line1.\r\n");

or like you said: appendLine

builder.AppendLine("Line1.");

and after that, depending on your consumer , you can replace the '\r\n' with a different new line string. For browser

<br/> tag.

Alex Pacurar
+1 Thanks Alex Pacurar!
Born To Learn
+2  A: 

AppendLine method of StringBuilder adds default line terminator to the end of appended string. The default line terminator is the current value of the Environment.NewLine property, which is "\r\n" for non-Unix platforms, or "\n" for Unix platforms. So what your WebMethod is trying to return looks so:

"Line1.\r\nLine2.\r\nLine3.\r\n".

However, the return value is serialized according to SOAP specifications by truncating "\r", and the result looks slightly different:

"Line1.\nLine2.\nLine3.\n".

If service consumer is running on a Windows platform it would probably ignore the single "\n" character as a garbage. Probable solutions:

  1. Encode return value into another format, e.g. into a byte array so: return builder.ToString().ToCharArray();

  2. Replace NewLine with another string that may be provided by the caller, e.g. into a BR tag: return builder.Replace(Environment.NewLine, "<br/>").ToString();

  3. Return array of lines or any other container with all lines separated.

SlavaGu
Thanks SlavaGu, yes that is exactly what is happen here, thanks for your good explanation. I think there is no way to do this with “ready to use” string result. I have to use different/modified line break. But I’ll accept this answer. Thanks :-)
Born To Learn
A: 

use environement.newline while appending.

KZoal