简体   繁体   English

C# 不要用逗号分割字符串

[英]C# Do not split string on comma

I am using Xamarin.Forms to create a data collection application.我正在使用 Xamarin.Forms 创建数据收集应用程序。 One particular feature of this app is to export the data via csv.此应用程序的一个特殊功能是通过 csv 导出数据。 When captured the data is written to a text file using the following method:捕获后,使用以下方法将数据写入文本文件:

 public void WriteToFile(string CompanyName, string Website, string FirsttName, string LastName, string JobTitle, string Phone, string Email, string Solution, string Notes, string ContactOwner, string EventName)
    {
        string path = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
        string filename = System.IO.Path.Combine(path, "Prospects.txt");
        string lineToBeAdded = string.Format("{0},{1},{2},{3},{4},{5},{6},{7},{8},{9},{10}", CompanyName, Website, FirsttName, LastName, JobTitle, Phone, Email, Solution, Notes, ContactOwner, EventName);
        File.AppendAllText(filename, lineToBeAdded + Environment.NewLine);


    }

My problem is that in the variable NOTES the user uses commas in their description which messes up the structure of the csv.我的问题是,在变量 NOTES 中,用户在他们的描述中使用了逗号,这弄乱了 csv 的结构。

How do I force ignore commas in this string?如何强制忽略此字符串中的逗号?

To escape comma warp each column in double quotes, to scape double qoutes use 2 double qoutes instead of each:要在双引号中转义逗号扭曲每列,要转义双引号,请使用 2 个双引号而不是每个:

 string lineToBeAdded = string.Format("\"{0}\",\"{1}\",\"{2}\",\"{3}\",\"{4}\",\"{5}\",\"{6}\",\"{7}\",\"{8}\",\"{9}\",\"{10}\"", 
CompanyName.Replace("\"","\"\""),
 Website.Replace("\"","\"\""),
 FirsttName.Replace("\"","\"\""),
 LastName.Replace("\"","\"\""),
 JobTitle.Replace("\"","\"\""),
 Phone.Replace("\"","\"\""),
 Email.Replace("\"","\"\""),
 Solution.Replace("\"","\"\""),
 Notes.Replace("\"","\"\""),
 ContactOwner.Replace("\"","\"\""),
 EventName.Replace("\"","\"\""));

Solution解决方案

Create this function:创建这个函数:

string GetCsvLine(params string[] fields) =>
   string.Join(",", fields.Select(x => $"\"{x.Replace("\"", "\"\"")}\""));

And call it like this, replacing the line in your example code that initializes "lineToBeAdded":并像这样调用它,替换示例代码中初始化“lineToBeAdded”的行:

string lineToBeAdded = GetCsvLine(CompanyName, Website, FirsttName, LastName, JobTitle, Phone, Email, Solution, Notes, ContactOwner, EventName);

Explanation解释

Refer here - RFC4180 - to the specification for CSV:请参阅此处 - RFC4180 - CSV 规范:

Summarizing:总结:

  • A field must be enclosed in double-quotes, if it contains a comma, a line break, or a double-quote.如果字段包含逗号、换行符或双引号,则必须将其括在双引号中。
  • Any double-quotes within a field must themselves be doubled.字段的任何双引号本身都必须加倍。
  • Bonus: using 'params' and LINQ allows you to call this method with a variable number of arguments, eliminating the need for a format string with the exact number of placeholders.奖励:使用“参数”和 LINQ 允许您使用可变数量的参数调用此方法,从而无需具有确切数量的占位符的格式字符串。

Also you don't have to use comma's, you can use a |此外,您不必使用逗号,您可以使用 | or something else the user doesn't use.或其他用户不使用的东西。

To make it even more friendly you can specify the delimiter in the first line, excel supports that I know.为了让它更友好,你可以在第一行指定分隔符,我知道 excel 支持。

sep=|
header1|header2|header3
1,2|2,3|3,4

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM