扫描图像并将其像 pdf 一样保存到数据库中 c#

Scan an image and save it like pdf into database c#

我正在创建一种扫描文档并将其另存为图像的方法。然后它会创建一个 pdf 文档,我将图像放在其中并将其正确保存到数据库中。问题是我只想在我的文件浏览器中保存 pdf,但扫描的图像也被保存了,我无法删除它。它给我错误:“该操作无法完成,因为该文件已在另一个程序中打开”。

我使用 Visual Studio 2019 和 SQL 服务器。

有没有另一种方法可以在不保存图像的情况下将 pdf 保存到数据库中?

这是代码:

internal static string EscanearDocumento(string pathImage, string path, PdfDocument doc)
{
   int count = 0;

WIA.CommonDialog wiaDiag = new WIA.CommonDialog();
var imageFile = wiaDiag.ShowAcquireImage(WiaDeviceType.ScannerDeviceType, WiaImageIntent.TextIntent, WiaImageBias.MaximizeQuality, "{00000000-0000-0000-0000-000000000000}", true, true, false);

while (File.Exists(pathImage + cont + ".png") || File.Exists(path + cont + ".pdf"))
{
   cont++;
}

pathImage = pathImage + cont + ".png";
path = path + cont + ".pdf";
try
{
   imageFile.SaveFile(pathImage);
   Image img = Image.FromFile(pathImage);

   PdfPage page = doc.AddPage();
   page.Orientation = PageOrientation.Portrait;
   XGraphics graphics = XGraphics.FromPdfPage(page);
   graphics.DrawImage(XImage.FromFile(pathImage), 0, 0);
   img.Dispose();
   } catch(NullReferenceException)
   {
      MessageBox.Show("Error");
   }

这是我用来扫描文档的方法:

internal static string EscanearDocumento(string path, PdfDocument doc)
        {
            int cont = 0;
            
            WIA.CommonDialog wiaDiag = new WIA.CommonDialog();
            try
            {
                ImageFile imageFile = wiaDiag.ShowAcquireImage(WiaDeviceType.ScannerDeviceType, WiaImageIntent.TextIntent, WiaImageBias.MaximizeQuality, "{00000000-0000-0000-0000-000000000000}", true, true, false);

                while (File.Exists(path + cont + ".pdf"))
                {
                    cont++;
                }
                path = path + cont + ".pdf";

                try
                {
                    byte[] imagenEnBytes = (byte[])imageFile.FileData.get_BinaryData();
                    using (MemoryStream ms = new MemoryStream(imagenEnBytes))
                    {
                        XImage imagen = XImage.FromStream(ms);
                        
                        PdfPage page = doc.AddPage();
                        page.Orientation = PageOrientation.Portrait;
                        XGraphics graficos = XGraphics.FromPdfPage(page);
                        graficos.DrawImage(imagen, 0, 0);
                    }
                } catch(NullReferenceException)
                {
                    MessageBox.Show("Error");
                }
            } catch (COMException er) {
                excepciones(er);
            }
            return path;
        }

我在我的主要 class 中使用它,通过这种方法将文档插入数据库:

private void AgregarDocumentos_Click(object sender, EventArgs e)
        {
            string text1= TextBox1.Text;
            string text2= TextBox2.Text;

            string query = "SELECT * FROM tableName WHERE p ='" + text1 + "'AND n ='" + text2+ "'AND documento is not null";
            SqlDataAdapter adapter = new SqlDataAdapter(query, con);
            DataTable dt = new DataTable();
            adapter.Fill(dt);

            if (dt.Rows.Count == 0)
            {
                Boolean found = false;
                try
                {
                    DeviceManager manejadorDisp = new DeviceManager();
                    DeviceInfo escanerDisponible = null;

                    for (int i = 1; i <= manejadorDisp.DeviceInfos.Count; i++)
                    {
                        if (manejadorDisp.DeviceInfos[i].Type != WiaDeviceType.ScannerDeviceType)
                        {
                            continue;
                        }
                        else
                        {
                            found = true;
                            string path = @"C:";
                            escanerDisponible = manejadorDisp.DeviceInfos[i];
                            Device dispositivo = escanerDisponible.Connect();
                            Item objetoEscaneado = dispositivo.Items[1];
                            PdfDocument doc = new PdfDocument();
                            
                            try
                            {
                                path = Escaner.EscanearDocumento(path, doc);
                                try
                                {
                                    DialogResult dialogResult = DialogResult.Yes;
                                    while (dialogResult == DialogResult.Yes)
                                    {
                                        dialogResult = MessageBox.Show("¿Quiere escanear un documento?", "", MessageBoxButtons.YesNo);
                                        if (dialogResult == DialogResult.Yes)
                                        {
                                            Escaner.EscanearDocumento(path, doc);
                                            doc.Close();

                                        }
                                        else if (dialogResult == DialogResult.No)
                                        {
                                            doc.Save(path);
                                            continue;
                                        }
                                    }

                                    var leer = File.ReadAllBytes(path);

                                    SqlCommand inserta = new SqlCommand("UPDATE tableName SET n = n, p = p, ni = ni, documento = @documento WHERE p ='" + text1 + "'AND n ='" + text2 + "';", con);
                                    inserta.Parameters.AddWithValue("@documento", read);
                                    con.Open();
                                    inserta.ExecuteNonQuery();
                                    con.Close();

                                    Process proceso = new Process();
                                    proceso.StartInfo = new ProcessStartInfo(path)
                                    {
                                        UseShellExecute = true
                                    };
                                    proceso.Start();

                                    MessageBox.Show("Inserted");
                                    break;
                                }
                                catch (InvalidOperationException)
                                {
                                    MessageBox.Show("Cannot save the file");
                                }
                            }
                            catch (FileNotFoundException)
                            {
                                MessageBox.Show("Not found");
                            }
                        }
                    }
                }
                catch (COMException er)
                {
                    Escaner.excepciones(er);
                }
                if(!found)
                {
                    MessageBox.Show("Not found");
                }
            }
            else
            {
                MessageBox.Show("");
            }
        }