在插值字符串C#中逃脱半隆
我将数据写入.csv文件,我需要正确读取以下表达式:
csvWriter.WriteLine($"Security: {sec.ID} ; Serial number: {sec.SecuritySerialNo}");
中间的半隆用于将序列号放在单独的单元格中。
问题在于,ID还可以包含分号并弄乱数据,因此我需要逃脱它。
我试图使用替换:
csvWriter.WriteLine($"Security: {sec.ID.Replace(";", "")} ; Serial number: {sec.SecuritySerialNo}");
尽管删除分号不是我想实现的目标,但我只想逃脱它们。
I am writing data to .csv file and I need the below expression to be read correctly:
csvWriter.WriteLine(quot;Security: {sec.ID} ; Serial number: {sec.SecuritySerialNo}");
the semicolon in between is used to put the serial number in a separate cell.
The problem is that ID can also contain semicolons and mess up the data, therefore I need to escape it.
I have tried to use replace:
csvWriter.WriteLine(quot;Security: {sec.ID.Replace(";", "")} ; Serial number: {sec.SecuritySerialNo}");
though deleting semicolons is not what I want to achieve, I just want to escape them.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
让我们再次强调,创建CSV文件的最佳方法是通过专业的CSV解析器库。
但是,仅解决您的问题提出的简单案例,您就可以在每个字段周围添加双引号。这应该足以向Excel解析器解释如何处理您的字段。
因此,以这种方式导出字段:
请注意,我删除了半隆周围的空白。重要的是,excel不会正确解析这条线
Let's emphasize again that the best way to create a CSV file is through a specialized CSV Parser library.
However, just to resolve the simple case presented by your question you could add double quotes around each field. This should be enough to explain to the Excel parser how to handle your fields.
So, export the fields in this way:
Notice that I have removed the blank space around the semicolon. It is important otherwise Excel will not parse the line correctly