将源代码格式保存为TXT文件

时间:2013-08-23 18:59:48

标签: c# webclient string-formatting

我正在尝试从网页中提取源代码并将其保存到文本文件中。但是,我想保留源代码的格式。

我的代码如下。

// 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);
            }
        }

我希望文本文件显示源代码,因为它在Messagebox中格式化。

Messagebox截图: enter image description here

文字文件截图: enter image description here

我如何才能使文本文档的格式与Messagebox中的格式相同?

3 个答案:

答案 0 :(得分:2)

我同意评论,但我只会添加一条说明。如果在Notepad ++中打开它,N ++将检测行结尾并很好地为您显示文件。在Notepad ++中,您可以进入菜单并将Line Endings更改为Windows。如果您重新保存并在记事本中打开它,它将正确显示。问题是基本记事本不理解不同的行结尾。

希望它有所帮助。

答案 1 :(得分:1)

问题是你下载的字符串只有LF的行结尾。 Windows标准是CRLF行结尾。众所周知,Windows Notepad支持 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

答案 2 :(得分:0)

试试这个:

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