2012-07-26 225 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常见的 “转义序列” 的列表: