问题在于,只有一部分写入文档,而不是所需的标题数。控制台输出正常。
这里代码:
using AngleSharp;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AngleSharp
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("ok start");
Mainpar();
Console.ReadKey();
}
static async Task Mainpar()
{
// Setup the configuration to support document loading
var config = Configuration.Default.WithDefaultLoader();
// Load the names of all The Big Bang Theory episodes from Wikipedia
var address = "https://en.wikipedia.org/wiki/List_of_The_Big_Bang_Theory_episodes";
// Asynchronously get the document in a new context using the configuration
var document = await BrowsingContext.New(config).OpenAsync(address);
// This CSS selector gets the desired content
var cellSelector = "tr.vevent td:nth-child(3)";
// Perform the query to get all cells with the content
var cells = document.QuerySelectorAll(cellSelector);
// We are only interested in the text - select it with LINQ
var titles = cells.Select(m => m.TextContent).ToArray();
var allnum = titles.Count();
System.IO.StreamWriter sw = new System.IO.StreamWriter(@"C:\bd.txt");
for (int i = 0; i <= allnum; i++)
{
sw.WriteLine(titles[i] + i);
Console.WriteLine(titles[i] + i);
}
}
}
}
不知道问题是什么。不同数量的标题写入文件,后者不完全。可能线程被阻止或程序只是关闭..我不明白它是如何取决于
答案 0 :(得分:0)
您应该正确关闭流。可能发生的是当程序关闭时强制关闭流而不刷新文件。请尝试换行使用using语句:
using (var sw = new System.IO.StreamWriter(@"C:\bd.txt"))
{
for (int i = 0; i <= allnum; i++)
{
sw.WriteLine(titles[i] + i);
Console.WriteLine(titles[i] + i);
}
}
using
语句确保正确关闭流并在完成使用后将其刷新到磁盘。
此外,由于您未在await
方法中使用MainPar
,也未在主方法中使用await
调用它,因此没有充分的理由对其进行标记async
。它应该是static void
。除非您异步调用它,否则只需将async
关键字添加到方法中就无济于事。如果您希望MainPar
真的是异步,可以使用StreamWriter.WriteLineAsync(string)
方法:
using (var sw = new System.IO.StreamWriter(@"C:\bd.txt"))
{
for (int i = 0; i <= allnum; i++)
{
await sw.WriteLineAsync(titles[i] + i);
Console.WriteLine(titles[i] + i);
}
}
然后您可以在Main方法中调用,如下所示:
static void Main(string[] args)
{
Task.Run(async () =>
{
Console.WriteLine("ok start");
await Mainpar();
Console.ReadKey();
}).GetAwaiter().GetResult();
}