Invalid length for a Base-64 char array or string in web method asp.net

279 Views Asked by At

I am converting image from string by FromBase64String in asp.net C#, but at that time it showing title error in web method.

Here is my code,

[WebMethod]
public static List<CustomerMortgageModel> GetProductList()
{
    string constr = ConfigurationManager.ConnectionStrings["connection"].ConnectionString;

    List<CustomerMortgageModel> customers = new List<CustomerMortgageModel>();
    Service service = new Service();

    using (SqlConnection con = new SqlConnection(constr))
    {
        string qrySelProductDetail = "select * from tbl_MortageDetail " + System.Environment.NewLine;
        
        using (SqlCommand cmd = new SqlCommand(qrySelProductDetail, con))
        {
            con.Open();
            using (SqlDataReader sdr = cmd.ExecuteReader())
            {
                while (sdr.Read())
                {
                    byte[] bytes = Convert.FromBase64String(sdr["DesignImage"].ToString());
                    System.Drawing.Image image;
                    using (MemoryStream ms = new MemoryStream(bytes))
                    {
                        image = System.Drawing.Image.FromStream(ms);
                    }

                    customers.Add(new CustomerMortgageModel
                    {
                        DesignImage = image.ToString()
                    });
                }
            }
            con.Close();
        }
        
    }
    return customers;
}

The error coming from this line

byte[] bytes = Convert.FromBase64String(sdr["DesignImage"].ToString());

1

There are 1 best solutions below

2
On

use

var base64Img = (string)sdr["DesignImage"];
if (string.IsNullOrEmpty(base64Img))
{
    throw new ArgumentException("'DesignImage' is null or empty");
}
byte[] bytes = Convert.FromBase64String(base64Img);

so you'll be sure of the column's type and that the string isn't empty, if you still get an error at 'Convert.FromBase64String' it's impossible to find the problem without having a sample of the invalid base64 content (but paste it here only if it doesn't contain private data)