How does New line works in MongoDB with C# .NET?

I have a collection and within the collection I have a data stored something like this.

{
  "_id": {
    "$oid": "01010101010101010"
  },
  "heading": {
    "desc": "Hello I am Vinicius. \\n I play for Real Madrid",
  }
}

I am using QuestPDF which prints the data from the Database and generates a pdf.

In my C# code I have something like this:

table.Cell().Column(1).Row(1).Text(dbFootbalCol.heading.desc);

The output I am expecting is:

Hello I am Vinicius. 
I play for Real Madrid

And What I see is:

Hello I am Vinicius. \n I play for Real Madrid

What I am doing wrong? Is C# ignoring the new line character?

Thanks in Advance.

Hi @Lakshmanan_Balasubramanian,

Welcome to the MongoDB community forums! If your string is stored as “Hello I am Vinicius. \n I play for Real Madrid”, the expected output via Console.WriteLine() in your C# application should be exactly the same “Hello I am Vinicius. \n I play for Real Madrid”. This is because MongoDB is simply storing the string containing the literal (\n as two characters in the string). If you want C# to interpret this as a newline, you would have to manually replace the characters as follows in your application:

var formatted = retrievedString.Replace("\\n", "\n");
Console.WriteLine(formatted);

Additionally, this depends on how you’re storing the string in the database. E.g If you use the MongoDB .NET/C# driver to insert a string like this (E.g “Hello I am Palmer. \n I play for Chelsea.”), the \n is interpreted by C# as a newline character and the string stored in MongoDB will be with the actual line break (without the characters \n).

So when you retrieve it and try to print it via Console.WriteLine(), it would display exactly as you expect above.

Hello I am Palmer. 
I play for Chelsea.

For your application, this isn’t the case I presume and the string is being stored/imported separately in your collection it seems :slight_smile: Hope that helps.

Thanks,

Rishit.

Hi, Thanks for your answer. I managed to solve this immediately after posting it here, I am new to community and I forgot to delete this post however I will leave this so that it is useful for others.

Yes, it totally depends on how the string is stored in the database. If “\n” is used, that should be replaced with “\n” within the C#. The other solution is to use “\n” directly in the database so that Reg.Replace(“\n”, “\n”) is not required in C#.

Thanks!

1 Like

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.