locked
Error: attempt to read protected memory RRS feed

  • Question

  • Hi, I'm using SaveFileDialog and it works fine when I call it for first time. But when I invoke the next time I always have an error message.

    This is in spanish:

    System.AccessViolationException: 'Intento de leer o escribir en la memoria protegida. A menudo, esto indica que hay otra memoria dañada.'

    The translation would be:

    Attempt to read or write the protected memory. This could indicate, there is a damage memory.

    I'm not so experienced programmer. Can you help me urgently???

    Thanks a lot

                SaveFileDialog1.Filter = "Archivos de Excel (*.xlsx)|*.xlsx"
                SaveFileDialog1.FileName = "Hola"
                Dim GrabarAchivo As New Boolean


                GrabarAchivo = (SaveFileDialog1.ShowDialog() = DialogResult.OK)



                If GrabarAchivo Then

    Thursday, August 13, 2020 8:26 PM

Answers

  • Hello,

    Using a module or class level variable for any connection object be it a OleDbConnection or a SqlClientConnection is bad for many reasons. The de facto standard is shown below (without a password but that doesn't change how the connection is put together).

    Public Class ExcelOperations
        Private mException As Boolean = False
        Public ReadOnly Property IsSuccessful() As Boolean
            Get
                Return mException = False
            End Get
        End Property
        Public Function Read(fileName As String, sheetName As String) As DataTable
            Dim dt As New DataTable
    
            Using cn As New OleDb.OleDbConnection With
                {
                .ConnectionString =
                    "Provider=Microsoft.ACE.OLEDB.12.0;" &
                    $"Data Source={fileName};" &
                    "Extended Properties=""Excel 12.0;IMEX=1;HDR=No;"""}
    
                Using cmd As New OleDb.OleDbCommand With
                    {
                    .CommandText =
                        "SELECT F1 As FirstName, F2 As MiddleName, F3 As LastName, " &
                        "F4 As Street, F5 As City, F6 As State, F7 As Postal, " &
                        $"F8 As EmailAddress FROM [{sheetName}]",
                    .Connection = cn}
    
                    Try
                        cn.Open()
                        dt.Load(cmd.ExecuteReader)
                        mException = False
                    Catch ex As Exception
                        mException = True
                    End Try
    
                End Using
            End Using
    
            Return dt
    
        End Function
    
    End Class
    
    My guess the issue you have is working with OleDb or a problem Excel file and not the actual code you wrote.


    Please remember to mark the replies as answers if they help and unmarked them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.

    NuGet BaseConnectionLibrary for database connections.

    StackOverFlow
    profile for Karen Payne on Stack Exchange

    Thursday, August 13, 2020 11:20 PM
  • Thanks a lot for your help.

    If I understood I don't have to declare my variables like this (as public):

     Public connRegistroDiario As New OleDb.OleDbConnection

    I should declare the variables in each module like this:

     Dim connRegistroDiario As New OleDb.OleDbConnection

    Do you think this is the solution form my issue?

    Again I thank you lot your answer

    Not public or Dim but this

    Using cn As New OleDb.OleDbConnection With . .

    I still believe the issue is not code but the Excel file or even how the project was built in regards to "Any CPU" vs x86 or x64 under project properties.


    Please remember to mark the replies as answers if they help and unmarked them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.

    NuGet BaseConnectionLibrary for database connections.

    StackOverFlow
    profile for Karen Payne on Stack Exchange

    Friday, August 14, 2020 1:05 AM
  • Finally I could find the solution to all my problems with my application. I was using Framework 4.7.2, I change it to 4 and all the problems was solutioned.

    Thanks to all people who wanted to help me 

    Wednesday, August 26, 2020 7:25 PM

All replies

  • Hi

    Here is an alternatibe. Try it out and see if it helps.

    NOTE: you may benifit by always using the bold lines in your projects.

    Option Strict On
    Option Explicit On
    Public Class Form1
      Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    
        Dim mySaveDialog As New SaveFileDialog
        With mySaveDialog
          .Filter = "Archivos de Excel (*.xlsx)|*.xlsx"
          .FileName = "Hola"
        End With
        If mySaveDialog.ShowDialog = DialogResult.OK Then
          Stop
        End If
    
      End Sub
    End Class


    Regards Les, Livingston, Scotland

    Thursday, August 13, 2020 9:14 PM
  • Thanks a lot for your answer. I changed Option Stric and Option Explicit in Tools -> Options - > VBDefaults, but the problem goes on.

    Thanks again.

    Thursday, August 13, 2020 9:32 PM
  • Thanks a lot for your answer. I changed Option Stric and Option Explicit in Tools -> Options - > VBDefaults, but the problem goes on.

    Thanks again.

    Thursday, August 13, 2020 9:32 PM
  • Hi

    I can't reproduce the issue you have - even using the code you posted. The issue must be from somewhere else in your code.  Have you tried single stepping? That at least would show where the problem is happening.

    BTW: I have had that exception a long time ago and as far as I know it actually doesn't have anything to do with corruted memory.


    Regards Les, Livingston, Scotland



    • Edited by leshay Thursday, August 13, 2020 9:54 PM
    Thursday, August 13, 2020 9:52 PM
  • Tanks a lot for your answer. I think the same as you. It doesn't have anything to do with corrupted memory.

    Trying to find a solution, I placed another button and invoke SaveFileDialog alone without problems. Then added part of the code of my real application. And could reproduce the error. 

    I could see the problem appears when I open a SQL database connection 

    I declared a Pablic variable 

        Public connRegistroDiario As New OleDb.OleDbConnection

    In some part of the program and I give a value

     connRegistroDiario = New OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + NameFileRegistroDiario + ";Persist Security Info=True;Jet OLEDB:Database Password=13439")

    And finally in the module I open the connection connRegistroDiario and after that I call SaveFileDialog. Then the error appears. Sometimes in first opportunity or in the second or third.

    I could found a solution by using other variable of the connection with the database.

        Dim connRegistroDiario2 As New OleDb.OleDbConnection

            connRegistroDiario2 = New OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + NameFileRegistroDiario + ";Persist Security Info=True;Jet OLEDB:Database Password=13579")

            connRegistroDiario2.Open()

    And without closing the connection I open the original connection

        Dim SaveFileDialog1 As New SaveFileDialog

            connRegistroDiario.Open()
            cmdRegistroDiario.Connection = connRegistroDiario
            cmdRegistroDiario.CommandType = CommandType.Text

    then I can call SaveFileDialog as many times as I want, but it's important to keep open the first connection (connRegistroDiario2). If I close this connection the problem appears agian.

    IT IS VERY CRAZY. I DON'T KNOW WHY IT IS LIKE THIS. BUT NOW I DON'T HAVE THE PROBLEM.

    If you have any explanation I will thank you

    Thanks a lot!!!!!!!!



    Thursday, August 13, 2020 10:34 PM
  • Hi

    Maybe someone else will offer some assistance as your code is much more related to DataBase. I am not a DataBase user at all.


    Regards Les, Livingston, Scotland

    Thursday, August 13, 2020 10:56 PM
  • Hello,

    Using a module or class level variable for any connection object be it a OleDbConnection or a SqlClientConnection is bad for many reasons. The de facto standard is shown below (without a password but that doesn't change how the connection is put together).

    Public Class ExcelOperations
        Private mException As Boolean = False
        Public ReadOnly Property IsSuccessful() As Boolean
            Get
                Return mException = False
            End Get
        End Property
        Public Function Read(fileName As String, sheetName As String) As DataTable
            Dim dt As New DataTable
    
            Using cn As New OleDb.OleDbConnection With
                {
                .ConnectionString =
                    "Provider=Microsoft.ACE.OLEDB.12.0;" &
                    $"Data Source={fileName};" &
                    "Extended Properties=""Excel 12.0;IMEX=1;HDR=No;"""}
    
                Using cmd As New OleDb.OleDbCommand With
                    {
                    .CommandText =
                        "SELECT F1 As FirstName, F2 As MiddleName, F3 As LastName, " &
                        "F4 As Street, F5 As City, F6 As State, F7 As Postal, " &
                        $"F8 As EmailAddress FROM [{sheetName}]",
                    .Connection = cn}
    
                    Try
                        cn.Open()
                        dt.Load(cmd.ExecuteReader)
                        mException = False
                    Catch ex As Exception
                        mException = True
                    End Try
    
                End Using
            End Using
    
            Return dt
    
        End Function
    
    End Class
    
    My guess the issue you have is working with OleDb or a problem Excel file and not the actual code you wrote.


    Please remember to mark the replies as answers if they help and unmarked them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.

    NuGet BaseConnectionLibrary for database connections.

    StackOverFlow
    profile for Karen Payne on Stack Exchange

    Thursday, August 13, 2020 11:20 PM
  • Thanks a lot for your help.

    If I understood I don't have to declare my variables like this (as public):

     Public connRegistroDiario As New OleDb.OleDbConnection

    I should declare the variables in each module like this:

     Dim connRegistroDiario As New OleDb.OleDbConnection

    Do you think this is the solution form my issue?

    Again I thank you lot your answer

    Friday, August 14, 2020 12:56 AM
  • Thanks a lot for your help.

    If I understood I don't have to declare my variables like this (as public):

     Public connRegistroDiario As New OleDb.OleDbConnection

    I should declare the variables in each module like this:

     Dim connRegistroDiario As New OleDb.OleDbConnection

    Do you think this is the solution form my issue?

    Again I thank you lot your answer

    Not public or Dim but this

    Using cn As New OleDb.OleDbConnection With . .

    I still believe the issue is not code but the Excel file or even how the project was built in regards to "Any CPU" vs x86 or x64 under project properties.


    Please remember to mark the replies as answers if they help and unmarked them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.

    NuGet BaseConnectionLibrary for database connections.

    StackOverFlow
    profile for Karen Payne on Stack Exchange

    Friday, August 14, 2020 1:05 AM
  • I think about your comment:

    "I still believe the issue is not code but the Excel file or even how the project was built in regards to "Any CPU" vs x86 or x64 under project properties"

    I don't know then, if I have something else besides the way to declare the variables with "using"

    If you agree, I'll change the way to declare the variables and if my problems goes on, I'll send you a new message.

    thanks a lot


    Friday, August 14, 2020 1:29 AM
  • Can you try the following code sample which has a .xlsx file using OleDb to read and update.

    https://1drv.ms/u/s!AtGAgKKpqdWjkRXg-fCaHjQqgm8M?e=RN9yCL


    Please remember to mark the replies as answers if they help and unmarked them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.

    NuGet BaseConnectionLibrary for database connections.

    StackOverFlow
    profile for Karen Payne on Stack Exchange

    Friday, August 14, 2020 4:56 PM
  • Finally I could find the solution to all my problems with my application. I was using Framework 4.7.2, I change it to 4 and all the problems was solutioned.

    Thanks to all people who wanted to help me 

    Wednesday, August 26, 2020 7:25 PM