An attempt was made to read or write protected memory. This is often an indication that other memory is damaged. when using OpenFileDialog

I am using an open file dialog that I have dragged from the toolbox to my form. Until recently, the dialog with the file worked fine.

I have searched high and low for an answer on the internet, but none of them work. I started a project on my home computer and then copied the entire project folder to my work computer so that I could work on it both at home and at work.

The file dialog works fine even now on my work computer, but after making a code change (at work) and copying the new project folder to my home computer, the problem occurs. This is not managed in TFS or any other common place. This is a private project that I am working on. The code where the problem occurs is as follows:

Thread th;        
private void btnUploadToDB_Click(object sender, EventArgs e)
{
    try
    {

        openFileDialog1.Title = "Select new data file";
        openFileDialog1.Filter = "Excel Files |*.xlsx";

        if (openFileDialog1.ShowDialog() == DialogResult.OK)
        {
            string filePath = openFileDialog1.FileName;
        }
        else if (DialogResult == DialogResult.None)
        {
            return;
        }

        th = new Thread(uploadToDB);
        Control.CheckForIllegalCrossThreadCalls = false;
        th.Start();
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
    finally
    {
        GC.Collect();
    }
}

      

The stack trace when an error occurs looks like this:

System.AccessViolationException was unhandled Message = An attempt was made to read or write protected memory. This is often an indication that other memory is damaged. Source = System.Windows.Forms Stack Traces: at System.Windows.Forms.FileDialogNative.IFileDialog.Show (parent IntPtr) at System.Windows.Forms.FileDialog.RunDialogVista (IntPtr hWndOwner) at System.Windows.Forms.FileDialog. (IntPtr hWndOwner) at System.Windows.Forms.CommonDialog.ShowDialog (owner of IWin32Window) at System.Windows.Forms.CommonDialog.ShowDialog () at Form1.Form1.btnUploadData_Click (object sender, EventArgs e) at C: \ Users \ User1 \ Documents \ Visual Studio 2010 \ Projects \ C # _Projects \ C # Projects \ Solution 1 \ Solution 1 \ Form1.cs: line 458 in System.Windows.Forms.Control.OnClick (EventArgs e) at System.Windows.Forms.Button.OnClick (EventArgs e) at System.Windows.Forms.Button.OnMouseUp (MouseEventArgs mevent) at System.Windows.Forms.Control.WmMouseUp (Message & m, MouseButtons button , Int32 clicks) to System.Windows.Forms.Control.WndProc (Message & m) to System.Windows.Forms.ButtonBase.WndProc (Message & m) to System.Windows.Forms.Button.WndProc (Message & m) to System.Windows.Forms.Control.ControlNativeWindow.OnMessage (Message & m) at System.Windows.Forms.Control.ControlNativeWindow.WndProc (Message & m) at System.Windows.Forms.NativeWindow.DebuggableCallback (IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam) at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW (MSG & msg) at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop (IntPtr dwComponentID, Int32 Reason, Int32 pvLoopData) System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner Reason, Application.RunMessageLoopInner Reason .ThreadContext.RunMessageLoop (Int32 reason, ApplicationContext context) at System.Windows.Forms.Application.Run (Form mainForm) at Form1.Program.Main () at C: \ Users \ User1 \ Documents \ Visual Studio 2010 \ Projects \ C # _Projects \ C # Projects \ Solution 1 \ Solution 1 \ Program.cs: Line 18 at System.AppDomain._nExecuteAssembly (RuntimeAssembly assembly, String [] args) at System.AppDomain.ExecuteAssembly (String assemblyFile, Evidence assemblySecurity, String [] args) in Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly () at System.Threading.ThreadHelper.ThreadStart_Context (object state) at System.Threading.ExecutionContext.Run (ExecutionContext executeContext, ContextCallback callback, object state, Boolean ignoreSyncCtx) at System.Threading.ExecutionContextxt. call ContextCallback, object state) in System.Threading.ThreadHelper.ThreadStart () InnerException:ThreadHelper.ThreadStart () InnerException:ThreadHelper.ThreadStart () InnerException:

Also, I tried to create an empty project on my home computer where the problem occurred and added openfiledialog in the same way and it works fine. The problem seems to be related only to this app, and so does it when it's on my home machine.

I am adding updateToDB method as requested. I changed some of the values, so there might be lines that don't make sense, however I believe this is not relevant to the problem.

private void uploadToDB()
{
    try
    {
        string values = "";
        string excelConString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source='" +
                filePath + "'; Extended Properties='Excel 12.0 Xml;HDR=Yes;IMEX=1;'";
        string excelSql = "select * from [Sheet1$]";
        string accessConString = GlobalOleDBCommands.DBconString;

        string accessSql = "delete from table1";
        GlobalOleDBCommands.CommandExecuteNonQuery(accessSql, accessConString);

        using (OleDbDataAdapter adap = new OleDbDataAdapter(excelSql, excelConString))
        {
            using (DataTable dt = new DataTable())
            {
                adap.Fill(dt);

                using (OleDbConnection accessCon = new OleDbConnection(accessConString))
                {
                    accessCon.Open();

                    for (int i = 0; i < dt.Rows.Count - 1; i++)
                    {

                        for (int j = 0; j <= dt.Columns.Count - 1; j++)
                        {
                            values = values.Trim() + dt.Rows[i][j] + ",";
                        }
                        values = Strings.Left(values, (Strings.Len(values) - 1));

                        string value1 = SplitAndReturnText(values, ",", 0);
                        string value2 = SplitAndReturnText(values, ",", 1);
                        string value3 = SplitAndReturnText(values, ",", 2);
                        string value4 = SplitAndReturnText(values, ",", 3);

                        accessSql = "insert into table1 (value1,value2,value3,value4) values(@value1,@value2,@value3,@value4)";

                        using (OleDbCommand dtToAccessCmd = new OleDbCommand(accessSql, accessCon))
                        {
                            dtToAccessCmd.Parameters.AddWithValue("@value1", value1);
                            dtToAccessCmd.Parameters.AddWithValue("@value2", value2);
                            dtToAccessCmd.Parameters.AddWithValue("@value3", System.Threading.Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase(value3.ToLower()));
                            dtToAccessCmd.Parameters.AddWithValue("@value4", value4);
                            try
                            {
                                dtToAccessCmd.ExecuteNonQuery();
                            }
                            catch (Exception)
                            {

                            }

                            this.lblProgress.Text = (i + "/" + ((dt.Rows.Count) - 1)).ToString();
                            this.lblProgress.Refresh();
                        }
                        // Reset value variable to null.
                        values = "";
                    }
                }
            }
        }

        accessSql = "select max(end_time) from table1 where user_name='" +
                    Environment.UserName + "'";

        DateTime start_time = Convert.ToDateTime(GlobalOleDBCommands.
        CommandExecuteScalar(accessSql, GlobalOleDBCommands.DBconString));
        DateTime end_time = DateTime.Now;
        double total_time = (end_time - start_time).TotalMinutes;

        string fieldValues = "start_time, end_time, user_name, task_name, total_time,task_count";
        accessSql = "insert into table1 (" + fieldValues + ") values ('" +
                    start_time + "','" + DateTime.Now + "','" + Environment.UserName +
                    "','Update to DB','" + total_time + "','1')";
        GlobalOleDBCommands.CommandExecuteNonQuery(accessSql, GlobalOleDBCommands.DBconString);

        MessageBox.Show("New data added ");
        this.lblProgress.Text = "";

    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }

      

Can someone please advise what is causing this issue as I cannot work on code changes at home for fear it won't work when I go to my work machine.

+3


source to share


1 answer


One of two things must happen to run the code on the deployment machine 1) The exact version of the Net library must be on both machines, including updates. 2) You must publish the application on the build machine, and then run the setup.exe folder created on the build machine on the deployment machine.



You just can't copy exe from one computer to another.

-2


source







All Articles