2016-09-28 35 views
-2

我是新來的文件系統。我需要創建一個簡單的csv文件,並需要在文件中寫入字符串並將其讀回來。如何在C#中創建一個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); 
     } 
    } 
+3

你有沒有研究這個呢?這是一個簡單的任務,很可能有很多很多的例子。 –

+0

問題到底是什麼? – HimBromBeere

+0

@ rory.ap我試過了,但是我得到的文件中有不需要的值被創建 –

回答

1

您可以使用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"); 
} 
+0

謝謝:)它的工作。 –

+0

沒問題!很高興我能幫上忙。 –

+0

這就是我試圖寫出條紋字符a ='a'; fs.Write(a [],1,1);現在我得到了點 –

1

您可以使用適當的擴展名創建特定的文件類型,在本例中爲「.csv」。 下面是一個使用filepath和一個隨機字符串的簡單例子。

using System; 
using System.IO; 

namespace CSVExample 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      string data = "Col1, Col2, Col2"; 
      string filePath = @"File.csv"; 
      File.WriteAllText(filePath, data); 
      string dataFromRead = File.ReadAllText(filePath); 
      Console.WriteLine(dataFromRead); 
     } 
    } 
} 

enter image description here

+0

這真是太棒了,謝謝。:) –

相關問題