I'm working on a console application where I need to send a command to an external executable. However, I'm stuck because I need to add double quotes before and after the command text to send it to the external executable for processing. After struggling for 15-20 minutes, I found a neat and clean solution for this issue.
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApplication { class Program { static void Main(string[] args) { string resstr = AddDoubleQuotesInstring("Append double quote to string"); } public static string AddDoubleQuotesInstring(string value) { //Put a string between double quotes. /// <param name="value">Value to be put between double quotes ex: foo</param> /// <returns>double quoted string ex: "foo"</returns> return "\"" + value + "\""; } } }
AddDoubleQuotesInstring which takes a string input and returns the input string enclosed within double quotes.
AddDoubleQuotesInstring Method:
Explanation:
For example, if value is "Append double quote to string", the method will return ""Append double quote to string"", where the string is enclosed within double quotes.
Let’s I want to save the text file with double string Then how we can achieve that task? Follow the below code.
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class GridView : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
WriteFileText();
}
public void WriteFileText()
{
string spath = System.Web.HttpContext.Current.Server.MapPath("~/FileStorage");
string path = spath + "/mytext.txt";
List<Person> _person = new List<Person>();
_person.Add(new Person { name = "Rahul", lastname = "Sharma", city = "New Delhi", });
_person.Add(new Person { name = "Tom", lastname = "Curz", city = "Tokyo" });
char seperator = ';';
StringBuilder sb = new StringBuilder();
foreach (Person obj in _person)
{
sb.Append("\"" + obj.name + "\"");
sb.Append(seperator);
sb.Append("\"" + obj.lastname + "\"");
sb.Append(seperator);
sb.Append("\"" + obj.city + "\"");
sb.AppendLine();
}
File.AppendAllText(path, sb.ToString());
}
}
class Person
{
public string name { get; set; }
public string lastname { get; set; }
public string city { get; set; }
}
Output: