【问题标题】:Loop Error including strings and variables循环错误,包括字符串和变量
【发布时间】:2018-11-12 00:41:54
【问题描述】:

我一直收到一个错误,比如当我有字符串时,它说它无法将 'byte[]' 转换为字符串。当我将它作为 var 时,它说的是同样的事情,但结果.txt 旁边的数据给我一个错误。

if (Lock.Contains("Mode: Data Grabber"))
{
    Console.WriteLine("Loading Data Grabber 2.0! Mode = Data Grabber!\n");
    Console.WriteLine("Enter the websites url!\n");
    Console.WriteLine("(\n) " + "(\n)");
    if (Option == Option)
    {
        WebClient wc = new WebClient();
        string data = wc.DownloadData(Option);
        Console.ForegroundColor = ConsoleColor.Green;
        Console.WriteLine("Downloading data from " + data);
        Thread.Sleep(3000);
        Console.WriteLine("\n");

        if (!File.Exists(Directory.GetCurrentDirectory() + @"/Results.txt"))
        {
            File.Create(Directory.GetCurrentDirectory() + @"/Results.txt");
        }

        File.WriteAllText(Directory.GetCurrentDirectory() + @"/Results.txt", data);
        Console.WriteLine("All data has been sent to the path");
    }
}

【问题讨论】:

  • 与实际问题无关(使用DownloadString而不是DownloadData),但if (Option == Option)看起来有点奇怪。
  • 请注意GetCurrentDirectory 可以在您的程序运行时更改,并且非管理员无法写入应用程序目录。咨询Error about finding the file ...

标签: c# web webclient


【解决方案1】:

给你:

将此代码string data = wc.DownloadData(Option); 替换为System.Text.Encoding.UTF8.GetString(wc.DownloadData(Option))

前提是对应文本的编码是UTF-8。

希望这会有所帮助。

【讨论】:

    【解决方案2】:

    您应该使用 WebClient 的 'DownloadString' 方法来获取字符串:

    string data = wc.DownloadString (Option);
    

    现在内容将是一个字符串。

    【讨论】:

      【解决方案3】:

      当你有一个byte[],即data时,你正试图写string

      string data = wc.DownloadData(Option);
      

      WebClient.DownloadData 返回一个byte[]

      public byte[] DownloadData (string address);
      

      试用:

      string data = wc.DownloadString (address);
      

      【讨论】:

      • 那么有没有办法修复或编辑它,让它工作?
      • 你从哪里下载什么?如果您尝试通过网络爬网并进行网络报废,请使用html-agility-pack.net
      猜你喜欢
      • 1970-01-01
      • 2013-12-30
      • 1970-01-01
      • 2010-12-12
      • 1970-01-01
      • 1970-01-01
      • 2013-11-18
      • 2013-04-01
      • 2018-01-02
      相关资源
      最近更新 更多