You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#随机密码生成器编译失败求助:代码问题排查与修正

修复你的C#随机密码生成器代码

我帮你排查了代码里的问题,主要是字符串转义错误导致编译失败,还有一些逻辑和命名上的小问题,下面是修正后的完整代码,以及问题的详细说明:

核心编译错误:字符串字面量转义问题

你的pwdCharArray初始化时,字符串里的双引号没有正确转义——C#里字符串中的双引号需要用\"表示,原代码里的:'\\",<>/?部分会导致编译器无法识别字符串的结束位置,这是编译失败的直接原因。

其他逻辑与优化点

  • 修正了属性与字段的命名冲突(原hasSymbols命名和ExcludeSymbols属性语义相反,容易混淆,直接简化为自动属性或调整字段名)
  • 替换了过时的RNGCryptoServiceProvider,改用.NET官方推荐的RandomNumberGenerator(兼容.NET Framework/.NET Core/.NET 5+全框架)
  • 调整了随机数生成的边界逻辑,避免出现索引越界或取不到最后一个字符的问题
  • 简化了部分属性的写法,让代码更简洁易读

修正后的完整代码

namespace WorkingCode.CodeProject.PwdGen {
    using System;
    using System.Security.Cryptography;
    using System.Text;

    public class PasswordGenerator {
        public PasswordGenerator() {
            Minimum = DefaultMinimum;
            Maximum = DefaultMaximum;
            ConsecutiveCharacters = false;
            RepeatCharacters = true;
            ExcludeSymbols = false;
            Exclusions = null;
            _rng = RandomNumberGenerator.Create();
        }

        protected int GetCryptographicRandomNumber(int lowerBound, int upperBound) {
            // 确保输入合法:lowerBound >= 0 且 lowerBound < upperBound
            if (lowerBound >= upperBound)
                throw new ArgumentOutOfRangeException(nameof(upperBound), "Upper bound must be greater than lower bound.");
            
            if (lowerBound == upperBound - 1)
                return lowerBound;

            uint range = (uint)(upperBound - lowerBound);
            uint maxSafeValue = uint.MaxValue - (uint.MaxValue % range);
            
            byte[] randomBytes = new byte[4];
            uint randomValue;
            
            do {
                _rng.GetBytes(randomBytes);
                randomValue = BitConverter.ToUInt32(randomBytes, 0);
            } while (randomValue >= maxSafeValue);

            return (int)(randomValue % range) + lowerBound;
        }

        protected char GetRandomCharacter() {
            int upperBound = _pwdCharArray.GetUpperBound(0);
            
            if (ExcludeSymbols) {
                // 只取字母和数字(索引0-61:26小写+26大写+10数字)
                upperBound = UBoundDigit;
            }

            // 注意:GetCryptographicRandomNumber返回<upperBound的值,所以要+1才能取到最后一个索引
            int randomIndex = GetCryptographicRandomNumber(_pwdCharArray.GetLowerBound(0), upperBound + 1);
            return _pwdCharArray[randomIndex];
        }

        public string Generate() {
            // 生成介于Minimum和Maximum之间的长度(包含两端)
            int passwordLength = GetCryptographicRandomNumber(Minimum, Maximum + 1);
            StringBuilder passwordBuffer = new StringBuilder(passwordLength);
            
            char lastChar = '\0';
            
            for (int i = 0; i < passwordLength; i++) {
                char nextChar = GetRandomCharacter();

                // 避免连续相同字符
                if (!ConsecutiveCharacters) {
                    while (nextChar == lastChar) {
                        nextChar = GetRandomCharacter();
                    }
                }

                // 避免重复字符
                if (!RepeatCharacters) {
                    while (passwordBuffer.ToString().IndexOf(nextChar) != -1) {
                        nextChar = GetRandomCharacter();
                    }
                }

                // 排除指定字符
                if (!string.IsNullOrEmpty(Exclusions)) {
                    while (Exclusions.IndexOf(nextChar) != -1) {
                        nextChar = GetRandomCharacter();
                    }
                }

                passwordBuffer.Append(nextChar);
                lastChar = nextChar;
            }

            return passwordBuffer.ToString();
        }

        public string Exclusions { get; set; }

        public int Minimum {
            get => _minSize;
            set {
                _minSize = value;
                if (_minSize < DefaultMinimum)
                    _minSize = DefaultMinimum;
            }
        }

        public int Maximum {
            get => _maxSize;
            set {
                _maxSize = value;
                if (_maxSize <= _minSize)
                    _maxSize = DefaultMaximum;
            }
        }

        public bool ExcludeSymbols { get; set; }
        public bool RepeatCharacters { get; set; }
        public bool ConsecutiveCharacters { get; set; }

        private const int DefaultMinimum = 6;
        private const int DefaultMaximum = 10;
        private const int UBoundDigit = 61; // 字母数字的最大索引(0-based)
        private readonly RandomNumberGenerator _rng;
        private int _minSize;
        private int _maxSize;
        // 修正了字符串转义:把双引号改为\",确保编译器能正确识别
        private readonly char[] _pwdCharArray = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789`~!@#$%^&*()-_=+[]{}\\|;:'\\\"<>/?".ToCharArray();
    }
}

运行说明

现在你可以编译这段代码,应该能正常生成符合要求的随机密码了。如果需要调整密码的规则(比如符号集、长度范围),直接修改对应的属性值即可。

内容的提问来源于stack exchange,提问作者enragedsweat

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.27 18:27:47