如何在 C# 中创建 CSV 文件

Nee*_*mar 2 c# csv filesystems file

我是文件系统新手。我需要创建一个简单的 csv 文件,并需要在文件中写入字符串并将其读回。

我在创建的文件中获取了一些 unicode 值。如何通过创建 csv 并从中读回来写入字符串值。

到目前为止我已经写了这个。这里需要一点点。

下面是我的代码。

        static void Main()
    {
        string folderName = @"D:\Data";
        string pathString = System.IO.Path.Combine(folderName, "SubFolder");
        System.IO.Directory.CreateDirectory(pathString);
        string fileName = System.IO.Path.GetRandomFileName();
        pathString = System.IO.Path.Combine(pathString, fileName);
        Console.WriteLine("Path to my file: {0}\n", pathString);

        if (!System.IO.File.Exists(pathString))
        {
            using (System.IO.FileStream fs = System.IO.File.Create(pathString))
            {
                {
                    byte a = 1;
                    fs.WriteByte(a);
                }
            }
        }

        // Read and display the data from your file.
        try
        {
            byte[] readBuffer = System.IO.File.ReadAllBytes(pathString);
            foreach (byte b in readBuffer)
            {
                Console.Write(b + " ");
            }
            Console.WriteLine();
        }
        catch (System.IO.IOException e)
        {
            Console.WriteLine(e.Message);
        }
    }
Run Code Online (Sandbox Code Playgroud)

Sir*_*Lot 5

您可以使用 Streamwriter 编写 csv 文件。您的文件将位于 bin/Debug 中(如果运行调试模式并且没有另外说明)。

 var filepath = "your_path.csv";
 using (StreamWriter writer = new StreamWriter(new FileStream(filepath,
 FileMode.Create, FileAccess.Write)))
 {
     writer.WriteLine("sep=,");
     writer.WriteLine("Hello, Goodbye");
 }
Run Code Online (Sandbox Code Playgroud)

  • 没问题!很高兴我能帮上忙。 (2认同)