【问题标题】:Index was outside the bounds of the array error索引超出了数组错误的范围
【发布时间】:2013-12-20 14:50:58
【问题描述】:

我目前正在使用我的输入文本框制作代理检查器。我收到 C# 错误:索引超出了 proxy(123.34.123.45:8080) 的数组范围。

我的代码将是...

string occoultProxy = "123.34.123.45:8080";
WebProxy proxy = new WebProxy(occoultProxy.Split(':')[0], Convert.ToInt32(occoultProxy.Split(':')[1])); //Error at this line
// WebProxy(string Host, int Port)

更新

我尝试了其他代码,但仍然有错误代码。请帮忙。

 string[] address = occoultProxy.Split(new[] { ':' });
 MessageBox.Show(address[0].ToString());
 MessageBox.Show(address[1].ToString());
 WebProxy proxyHTTP = new WebProxy(address[0], Convert.ToInt32(address[1]));

输出

123.34.345.23 <!-- Some Proxy here, seems good here -->
IndexOutOfRangeException was unhandled( Index was outside the bounds of the array.)

【问题讨论】:

  • 它对我有用。获取 occoultProxy 是否有问题?
  • 我猜occoultProxy 的值是一个没有端口号的IP。
  • 我已经尝试过您的示例,并且运行没有问题。你确定你传递给语句的字符串总是包含分号吗?因为您让用户输入地址,所以您应该检查字符串中的分号。

标签: c#


【解决方案1】:

你的输入不能有端口段,你可以这样处理:

WebProxy proxy = new WebProxy(new Uri("http://" + occoultProxy)); 

【讨论】:

  • 或设置端口为80
【解决方案2】:

这对你有用吗?

        var occoultProxy = "123.34.123.45:8080";
        var parts = occoultProxy.Split(':');

        if (parts.Length == 2)
        {
            var proxy = new WebProxy(parts[0], Convert.ToInt32(parts[1]));
        }
        else
        {
            throw new AnExceptionToHandleInYourUi();
        }

【讨论】:

    【解决方案3】:

    String.Split() 不采用单个字符作为参数。见String.Split

    尝试将您的代码更改为

    string[] address = occoultProxy.Split(new[] {':'});
    WebProxy proxy = new WebProxy(address[0], Convert.ToInt32(address[1]));
    

    【讨论】:

    • 存在具有params char[] 参数的重载。 public string[] Split( params char[] separator )。你可以像occoultProxy.Split(':')occoultProxy.Split(':', '.') 一样使用任意数量的参数来调用它。
    • 是的,发帖后才意识到。我想我应该先运行代码。不过,我一直使用 new[] {''} 语法。
    【解决方案4】:

    如果您尝试使用本地 ip 连接本地代理,请检查 occoultProxy 的值是否为 "::1"。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-09-18
      • 1970-01-01
      • 2014-03-09
      • 2013-12-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多