NFe.Components.CNPJ.Validate C# (CSharp) Method

Validate() public static method

valida o CNPJ
public static Validate ( string cnpj ) : bool
cnpj string
return bool
        public static bool Validate(string cnpj)
        {
            if (string.IsNullOrEmpty(cnpj)) return false;

            try
            {
                #region Valida
                string Cnpj_1 = cnpj.Substring(0, 12);
                string Cnpj_2 = cnpj.Substring(cnpj.Length - 2);
                string Mult = "543298765432";
                string Controle = String.Empty;
                int Soma = 0;
                int Digito = 0;

                for (int j = 1; j < 3; j++)
                {

                    Soma = 0;

                    for (int i = 0; i < 12; i++)
                        Soma += int.Parse(Cnpj_1.Substring(i, 1)) * int.Parse(Mult.Substring(i, 1));

                    if (j == 2) Soma += (2 * Digito);
                    Digito = ((Soma * 10) % 11);
                    if (Digito == 10) Digito = 0;
                    Controle = Controle + Digito.ToString();
                    Mult = "654329876543";

                }

                if (Controle != Cnpj_2)
                {
                    return false;
                }
                else
                {
                    return true;
                }
                #endregion
            }
            catch
            {
                return false;
            }

        }
        #endregion

Usage Example

示例#1
0
文件: CNPJ.cs 项目: tassio1125/Nfe
        private CNPJ(string cnpj)
        {
            if (cnpj.Length == 0)
            {
                return;
            }

            cnpj = Functions.OnlyNumbers(cnpj, ".,-/").ToString();
            if (CNPJ.Validate(cnpj) == false)
            {
                throw new ExceptionCNPJInvalido(cnpj);
            }
            this.mValue = cnpj;
        }