我试图从网页中提取源代码,并将其保存到文本文件中。但是,我想保留源代码的格式。
我的代码如下。
// 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屏幕截图:

文本文件屏幕截图:

如何使文本文档的格式与Messagebox中的格式相同?
发布于 2013-08-24 03:05:47
我同意这个评论,但我只需要补充一句。如果您在Notepad++中打开它,N++将检测行尾并为您很好地显示文件。在Notepad++中,您可以进入菜单并将线条端点更改为窗口。如果您随后重新保存它并在记事本中打开它,它将正确显示。问题是基本记事本不能理解不同的行尾。
希望能有所帮助。
发布于 2013-08-24 04:09:47
问题是,您正在下载的字符串只有LF-only行结尾。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。
发布于 2013-08-24 03:35:03
试试这个:
string[] lines = s.Split('\n');
System.IO.File.WriteAllLines(@"C:\Users\user\Dropbox\Personal Projects\WriteLines.txt", lines);https://stackoverflow.com/questions/18410028
复制相似问题