如何在C#中将互联网搜索输出打印到visual studio控制台



所以我正在开发一个c#程序,该程序旨在每隔1到100分钟的随机时间执行一次随机的谷歌搜索。然而,在运行程序时,我注意到CPU使用率从未改变,搜索也没有输出,尽管有一个将结果写入控制台的命令。我想知道如何在Visual Studio中将谷歌搜索结果打印到输出控制台?谢谢

private void googlesearch_DoWork(object sender, DoWorkEventArgs e)
{
MessageBox.Show("Random google search will be conducted between 1 am and 12 pm. Times will be sporadic.");

Random random = new Random();
TimeSpan start = TimeSpan.FromHours(1);
TimeSpan end = TimeSpan.FromHours(12);
int maxMinutes = (int)((end - start).TotalMinutes);
for (int i = 0; i < 100; ++i)
{
int minutes = random.Next(maxMinutes);
TimeSpan t = start.Add(TimeSpan.FromMinutes(minutes));
// Do something with t...
string uriString = "http://www.google.com/search";

WebClient webClient = new WebClient();
Random r = new Random();
string[] words = { "man", "rat", "cow", "chicken", "confuse", "cool", "space news", "science", "holiday", "chickens", "travel", "europoe", "USA", "president", "cool stuff", "world news", "donald trump", "politics", "space", "astronomy", "radio", "cool stuff", "USA News", "tell me a funny joke", "do a barrel rool", "mario and luigi", "radio", "abcdefghijklomnopqrstuvwxyz", "popular computer games", "graphics cards", "performance", "sports news", };
Console.WriteLine(words[r.Next(0, words.Length)]);

string word = words[r.Next(0, words.Length)];
NameValueCollection nameValueCollection = new NameValueCollection();
nameValueCollection.Add("q", word);
webClient.QueryString.Add(nameValueCollection);
Console.WriteLine(uriString);


我不知道"Visual Studio控制台";,但我知道如何让控制台出现在C#WPF程序中(几乎可以保证也是WinExe程序,包括WinForms(。这将用于开发,但很可能不是部署。

在项目文件中,将OutputTypeWinExe更改为仅Exe,并添加一行DisableWinExeOutputInference设置为true。正如我的一个项目中的这个片段所示。

<PropertyGroup>
<OutputType>Exe</OutputType>
<DisableWinExeOutputInference>true</DisableWinExeOutputInference>
<TargetFramework>net6.0-windows</TargetFramework>
<UseWPF>true</UseWPF>
</PropertyGroup>

WinForms程序中,您会看到UseWinForms而不是UseWPF。这是应该的。

所有这些都是.NET 5.NET 6以及新的项目格式。也许这在.NET Core 3中也可用,但如果感兴趣,您必须对此进行调查。如果您使用的是较旧的.NET平台和/或项目格式,请考虑更新。

控制台窗口将与主窗口一起出现。您可以关闭任一窗口来关闭应用程序。如果您遇到关闭代码未运行的情况,请告诉我,我也会详细介绍。

最新更新