在插值字符串C#中逃脱半隆

发布于 2025-02-09 16:04:22 字数 385 浏览 2 评论 0原文

我将数据写入.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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

许一世地老天荒 2025-02-16 16:04:22

让我们再次强调,创建CSV文件的最佳方法是通过专业的CSV解析器库。
但是,仅解决您的问题提出的简单案例,您就可以在每个字段周围添加双引号。这应该足以向Excel解析器解释如何处理您的字段。

因此,以这种方式导出字段:

csvWriter.WriteLine($"\"Security: {sec.ID}\";\"Serial number: {sec.SecuritySerialNo}\""); 

请注意,我删除了半隆周围的空白。重要的是,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:

csvWriter.WriteLine(
quot;\"Security: {sec.ID}\";\"Serial number: {sec.SecuritySerialNo}\""); 

Notice that I have removed the blank space around the semicolon. It is important otherwise Excel will not parse the line correctly

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文