如何在文本文件中写入url [英] how to write the url in a text file
问题描述
我是c sharp的新人。
我创建了一个带有文本框和按钮的表单。我希望当我提供任何网址并点击按钮代码生成该html页面的网址。
这在控制台应用程序中运行良好bt现在我想创建一个txt文件并保存网址。这个代码创建了一个文件,它太大了700mb而无法打开。
这是我的代码。
I am new in c sharp.
I have created a form that have a text box and a button. I want that when I give any web address and click the button the code generate the url of that html page.
this runs fine in console application bt now I want to creat a txt file and save the url. this code creat a file bt it too huge like 700mb and unable to open.
this is my code.
WebClient client = new WebClient();
string html = client.DownloadString(textBox1.Text);
HtmlTag tag;
HtmlParser.HtmlParser parse = new HtmlParser.HtmlParser(html);
while (parse.ParseNext("a", out tag))
{
string value;
if (tag.Attributes.TryGetValue("href", out value))
{
fs = new FileStream("URL.txt", FileMode.Create, FileAccess.Write);
sw=new StreamWriter(fs);
while(true)
{
sw.WriteLine(value);
}
}
sw.Close();
MessageBox.Show("Done");
}
我在做什么错误..
What mistak I am doing..
推荐答案
我认为问题在于以下代码
Problem I think lies in following code
while(true)
{
sw.WriteLine(value);
}
这将永远持续下去,没有休息
你不要''我猜这里需要一个循环循环。
希望有帮助
Milind
This will keep going forever, there is no break
You don''t need a while loop here I guess.
Hope that helps
Milind
你有这里有两个问题。首先,为HTML中找到的每个链接覆盖文件,然后构建一个无限循环写入该文件。以下是修补程序的代码:
You have two issues here. First you''re overwriting your file for each and every link you found in the HTML and secondly you built an infinite loop writing to that file. Here is your code with the fixes:
WebClient client = new WebClient();
string html = client.DownloadString(textBox1.Text);
HtmlTag tag;
HtmlParser.HtmlParser parse = new HtmlParser.HtmlParser(html);
fs = new FileStream("URL.txt", FileMode.Create, FileAccess.Write);
sw = new StreamWriter(fs);
while (parse.ParseNext("a", out tag))
{
string value;
if (tag.Attributes.TryGetValue("href", out value))
{
//while(true) // infinite loop must be removed
//{ // you only want to write the href attribute's value once
sw.WriteLine(value);
//}
}
}
// When the all anchor tags have been parsed close the file and show the "Done!" message.
sw.Close();
MessageBox.Show("Done!");
问候,
Manfred
Regards,
Manfred
这篇关于如何在文本文件中写入url的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!