C#C
C#•2y ago
MarcoART_

How to insert an image from a MediaPicker into my database in C# (MAUI)

Hello! 🙂 I'm new to MAUI and I'm facing challenges trying to insert an image from a MediaPicker into my database.

What I do is obtain either my byte array using these lines:

await stream.CopyToAsync(memoryStream);
ImageData = memoryStream.ToArray();
photoPreview.Source = ImageSource.FromStream(() => new MemoryStream(ImageData));

or obtain the data in a base64 string value using this line:

base64string = Convert.ToBase64String(ImageData);


The problem is, once I obtain these values that I need to insert into my database, and I execute the insert query, I'm getting this error:

Microsoft.Data.SqlClient.SqlException: 'A transport-level error has occurred when receiving results from the server. (provider: TCP Provider, error: 0 - Success)'

This only happens if i'm including the image in the query, if I eliminate it, the other data can be inserted perfectly without showing me any error.

This is my query:

byte[] bytesImagen = Convert.FromBase64String(base64string);

string cadena = @"Insert into Marco.CatUsuarios (Usuario, Nombre, Contrasena, NumTelefono, Imagen2, Ubicacion, Longitud, Latitud) values (@Usuario, @Nombre, @Contrasena, @NumTelefono, @Imagen2, @Ubicacion, @Longitud, @Latitud)";
 SqlCommand comando = new SqlCommand(cadena, conexion);

 comando.Parameters.AddWithValue("@Usuario", Usuario.Text);
 comando.Parameters.AddWithValue("@Nombre", Nombre.Text);
 comando.Parameters.AddWithValue("@Contrasena", Contrasena.Text);
 comando.Parameters.AddWithValue("@NumTelefono", NumTelefono.Text);
 comando.Parameters.AddWithValue("@Imagen2", bytesImagen);

 comando.ExecuteNonQuery();


And this is my connection string:

string connectionString = "Data Source=MyDataSource;Initial Catalog=MyInitialCatalog; User ID= MyUserID; Password = MyPassword; TrustServerCertificate=true;";


Thank You!
Was this page helpful?