c#编写/读取CSV

本文关键字:CSV 读取 编写 | 更新日期: 2023-09-27 18:15:07

我正在用c#编写一个程序。有了这个程序,我打算从文本框中写入值到CSV文件。不过到目前为止这是可行的。只有像这样粘贴在一起的值:

hellobye|
hello (TextBox1)
bye (TextBox2)

我怎么知道它们总是出现在新的一行?我已经试过环境了。换行,就是不能工作。

这是我到目前为止的代码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace test
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        private void button1_Click(object sender, EventArgs e)
        {
            if (textBox1.Text.Length != 0)
            {
                String input = textBox1.Text + textBox2.Text;
                string[] lines = {input  + "|" };
                System.IO.File.AppendAllLines(@"c:'output.csv", lines);
                textBox1.Clear();
                textBox2.Clear();
            }
          }
    }
}

c#编写/读取CSV

您可以使用StreamWriter。WriteLine方法的使用示例:

using System;
using System.IO;
class Test
{
    public static void Main()
    {
        string path = @"c:'temp'MyTest.txt";
        if (!File.Exists(path))
        {
            // Create a file to write to. 
            using (StreamWriter sw = File.CreateText(path))
            {
                sw.WriteLine("Hello");
                sw.WriteLine("And");
                sw.WriteLine("Welcome");
            }
        }
        // Open the file to read from. 
        using (StreamReader sr = File.OpenText(path))
        {
            string s = "";
            while ((s = sr.ReadLine()) != null)
            {
                Console.WriteLine(s);
            }
        }
    }
}

所以如果我是正确的,你当前的输出是"hellobye|"

,但你希望它是你好再见

所以,如果你正在创建一个csv,那么你会想要用逗号来分隔你的元素,然后为行插入换行符。所以一个快速控制台应用程序应该是这样的:

    static void Main(string[] args)
    {
        string string1 = "hello";
        string string2 = "bye";
        string[] lines =
            {
                string1 + 
                Environment.NewLine + 
                string2
            };
        System.IO.File.AppendAllLines(@"c:'output.csv", lines);
    }

其中string1 &String2只是作为文本框

的输出

这就是你的问题:

String input = textBox1.Text + textBox2.Text;

您将两个文本框的内容集中到一个单词中,之后系统将无法判断一个单词的结束位置和下一个单词的开始位置。