2013-08-23 73 views
0

我試圖從網頁中提取源代碼並將其保存到文本文件中。但是,我想保留源代碼的格式。將源代碼格式保存爲TXT文件

我的代碼如下。

// this block fetches the source code from the URL entered. 
     private void buttonFetch_Click(object sender, EventArgs e) 
     { 
      using (WebClient webClient = new WebClient()) 
      { 
       string s = webClient.DownloadString("http://www.ebay.com"); 

       Clipboard.SetText(s, TextDataFormat.Text); 

       string[] lines = { s }; 
       System.IO.File.WriteAllLines(@"C:\Users\user\Dropbox\Personal Projects\WriteLines.txt", lines); 

       MessageBox.Show(s.ToString(), "Source code", 
       MessageBoxButtons.OKCancel, MessageBoxIcon.Asterisk); 
      } 
     } 

我想讓文本文件顯示源代碼,因爲它是在消息箱中格式化的。

消息框截圖: enter image description here

文本文件截圖: enter image description here

我怎麼會去獲取文本文檔的格式是一樣的消息框?

+0

用記事本++打開它,它應該工作。 由於一些奇怪的原因,記事本想要在它讀取新行的方式上有所不同http://notepad-plus-plus.org/如果這種方法可行並且對您而言可以,我會將其添加爲答案,否則我會只是把它保留在評論中 –

回答

2

我同意評論,但我會添加一個便條。如果您在Notepad ++中打開它,N ++將會檢測到行結尾併爲您顯示文件。在Notepad ++中,你可以進入菜單並將行結束符更改爲Windows。如果您然後重新保存並在記事本中打開它,它會看起來正確。問題是基記事本不能理解不同的行尾。

希望它有幫助。

0

試試這個:

string[] lines = s.Split('\n'); 
System.IO.File.WriteAllLines(@"C:\Users\user\Dropbox\Personal Projects\WriteLines.txt", lines); 
1

的問題是,你下載的字符串有LF-只有行尾。 Windows標準是CRLF行結尾。 Windows記事本是堅決支持只有 CRLF行結局。其他編輯器,包括Visual Studio,正確處理純LF版本。

您可以將文本轉換爲CRLF行結束很輕鬆地:

string s = webClient.DownloadString("http://www.ebay.com"); 
string fixedString = s.Replace("\n", "\r\n"); 
System.IO.File.WriteAllText("filename", fixedString); 
MessageBox.Show(fixedString, "Source code", 
      MessageBoxButtons.OKCancel, MessageBoxIcon.Asterisk); 

還請注意,這是沒有必要調用ToString在一根繩子上。