2012-07-26 233 views
5

我在寫入製表符分隔字符串到txt文件時出現問題。從c#.net寫入製表符分隔txt文件

//This is the result I want:  
First line. Second line. nThird line. 

//But I'm getting this: 
First line./tSecond line./tThird line. 

下面是我的代碼,我把這個字符串被寫入到txt文件:

string word1 = "FirstLine."; 
string word2 = "SecondLine."; 
string word3 = "ThirdLine."; 
string line = word1 + "/t" + word2 + "/t" + word3; 

System.IO.StreamWriter file = new System.IO.StreamWriter(fileName, true); 
file.WriteLine(line); 

file.Close(); 

回答

15

使用\t爲製表符。使用String.Format可能會提供更具可讀性的選項:

line = string.Format("{0}\t{1}\t{2}", word1, word2, word3); 
0

使用\t/t的字符串標籤。所以你的字符串line應該是:

string line = word1 + "\t" + word2 + "\t" + word3; 

如果你這樣做:

Console.WriteLine(line); 

輸出爲:

FirstLine.  SecondLine.  ThirdLine. 
+0

否..使用「\ t」。 「\\ t」逃脫了斜線...... – 2012-07-26 03:26:33

+0

@EricJ。,絕對正確。我不知道我在想什麼 – Habib 2012-07-26 03:27:41

4

要寫出你需要使用"\t"製表符。它是一個反斜槓(在回車鍵上方),不是正斜槓。

所以,你的代碼應該閱讀:

string line = word1 + "\t" + word2 + "\t" + word3; 

對於它的價值,這裏就像"\t" = TAB常見的 「轉義序列」 的列表: