2013-10-25 76 views
0

我是新來的C#文件處理,我正在做一個非常簡單的程序。代碼如下:爲什麼換行符不起作用?

class MainClass 
{ 
    public static void Main() 
    { 
     var sw = new StreamWriter("C:\\Users\\Punit\\Desktop\\hello.txt"); 
     sw.Write("HelloWorld" +Environment.NewLine); 
     sw.Write("ByeWorld"); 
     sw.Close(); 

     Console.ReadLine(); 
    } 
} 

上面的代碼產生以下預期的結果在文本文件中:

HelloWorld 
ByeWorld 

我也寫了略加修改的代碼版本是這樣的:

class MainClass 
{ 
    public static void Main() 
    { 
     var sw = new StreamWriter("C:\\Users\\Punit\\Desktop\\hello.txt"); 
     sw.Write("HelloWorld\n"); 
     sw.Write("ByeWorld"); 
     sw.Close(); 

     Console.ReadLine(); 
    } 
} 

這裏代替使用

Environment.Newline 

我直接在「HelloWorld」行中添加了「\ n」。 這產生以下輸出(INT文本文件):

HelloWorldByeWorld 

我的問題是,爲什麼不工作的代碼的第二塊? (不生產在文本文件中的新行)

+1

翻譯C#自然語言:因爲'\在您的工作環境中,n'不會被解釋爲* New Line Feed * t :) – Alireza

+8

它是Windows上的'\ r \ n'。 –

+3

我在這裏猜測:您正在用記事本查看結果。記事本不會將單獨的U + 000A解釋爲換行符,只有U + 000D,U + 000A,因此您寫入文件*的內容是*,但您不會這樣看。至少不在記事本中。在任何像樣的文本編輯器中, – Joey

回答

6

請儘量

StreamWriter sw = new StreamWriter("C:\\Users\\Punit\\Desktop\\hello.txt"); 
    sw.Write("HelloWorld \r\n"); 
    sw.Write("ByeWorld"); 
    sw.Close(); 
    Console.ReadLine(); 

你可以讀它here

+1

感謝您的解決方案 –

+0

@Pratik隨時 – Rohit

1

將其更改爲 'sw.WriteLine'。像C++一樣,它調用換行符。你也可以 閱讀: Create a .txt file if doesn't exist, and if it does append a new line

+0

感謝您的解決方案,我試過了,它工作正常。我想知道原因,爲什麼「\ n」不起作用。 –

+0

嘗試閱讀此:http://stackoverflow.com/questions/1885900/order-of-carriage-return-and-new-line-feed –

2

您還可以

sw.WriteLine("HelloWorld"); 
sw.WriteLine("ByeWorld"); 
1

試試

sw.Write("HelloWorld\\n"); 

,而不是

sw.Write("HelloWorld\n");