System.ArgumentOutOfRangeException: '索引和长度必须指向字符串中的一个位置.在 C# 中 [英] System.ArgumentOutOfRangeException: 'Index and length must refer to a location within the string. in c#

查看:69
本文介绍了System.ArgumentOutOfRangeException: '索引和长度必须指向字符串中的一个位置.在 C# 中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

        string input = "";
        string result = "";
        if (Directory.Exists(Path.GetDirectoryName(filePath)))
        {
            if (File.Exists(filePath))
            {
                input = File.ReadAllText(filePath).ToString();
                List<byte> bList = new List<byte>();
                for (int i = 0; i < input.Length; i += 8)
                {
                    bList.Add(Convert.ToByte(input.Substring(i, 8), 2));
                }
                result = Encoding.UTF8.GetString(bList.ToArray());
                return result;

            }

异常发生在子字符串for循环内帮我摆脱这个异常.提前致谢

Exception occurs in Substring inside the for loop Help me to get rid of this exception. Thanks in Advance

推荐答案

您正在尝试访问子字符串,但未验证字符串中是否有足够的字符来执行此操作.

You are trying to access a substring without verifying that there are enough characters in the string to do so.

假设文件包含 6 个字符.这意味着 input.Length 是 6. for 循环的第一次迭代将使这个方法调用: input.Substring(0, 8).但是,该字符串中只有 6 个字符,因此您会收到 ArgumentOutOfRangeException.

Let's say the file contains 6 characters. That means input.Length is 6. The first iteration of the for loop will make this method call: input.Substring(0, 8). However, the string only has 6 characters in it, so you get an ArgumentOutOfRangeException.

这篇关于System.ArgumentOutOfRangeException: '索引和长度必须指向字符串中的一个位置.在 C# 中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆