试图读取受保护的内存。这通常表明内存已损坏。 [英] Attempted to read wirte protected memory .this is often an indication that memory is corrupted.

查看:72
本文介绍了试图读取受保护的内存。这通常表明内存已损坏。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,



请解决我的问题

我遇到同样的错误,在我的情况下,我有一个组合框在我的窗体中控制,还打开文件对话框和按钮打开文件进行选择。用户可以从openfile对话框和组合框中的文件中选择CSV文件,我使用oledb连接来读取excel文件,因为我需要将我的csv转换为excel,然后从excel表返回一个数据表。当我从组合框中选择一个文件然后第一次使用浏览按钮时它会抛出此异常,否则我从第一次浏览时选择一个文件然后执行此操作它成功运行。任何人都可以建议我如何解决这个例外。





如果您对情况不清楚,请退回..

并且如果可能的话还原为解决方案。

Hi all,

Please resolve my issue
I am getting the same error while in my case , I have a combo box control in my form and also open file dialog and button to open the file for selection. User can select CSV files from both openfile dialog and files in combobox and i am using oledb connection to read a excel file and as i needed to convert my csv to excel and then return a datatable from excel sheet . when ever i select a file from combobox and then use browse button for first time it throw this exception otherwise i have select a file from browse the first time an d then perform this operation it works successfully. Can anyone suggest me how to resolve this exception.


Please revert back if you are nt clear with situation..
and if possible revert with solution .

推荐答案

检查这些(包括已解决的线程),希望其中任何一个都能解决这个问题。

尝试读取或写入受保护的内存这通常表示其他内存已损坏 [ ^ ]

尝试读取或写入pr保护记忆。这通常表明其他内存已损坏。 [ ^ ]

System.AccessViolationException通过catch异常语句未处理 [ ^ ]

System.AccessViolationException未处理 [ ^ ]

accessviolationexception未处理 [ ^ ]

A类日:System.AccessViolationException [ ^ ] 如何处理错误:System.AccessViolationException:尝试读取或写入受保护的记忆这通常表明其他内存已损坏 [ ^ ]

System.AccessViolationException [ ^ ]
Check these(including solved threads), hope any one of these will solve this issue.
Attempt to read or write Protected Memory This is often an indicating that other memory is corrupt[^]
Attempted to read or write protected memory. This is often an indication that other memory has been corrupted.[^]
System.AccessViolationException unhandled by catch exception statement[^]
System.AccessViolationException was unhandled[^]
accessviolationexception was unhandled[^]
A Class A Day: System.AccessViolationException[^]how to deal with the error: System.AccessViolationException: Attempted to read or write protected memory. This is often an indication that other memory is corrupt[^]
System.AccessViolationException[^]


我有一个读取CSV的ReadCSv类,我通过选择的组合框或浏览文件传递路径。最初在加载过程中,我有一个从combobox中选择的文件作为默认文件,当我选择组合框的选择索引然后浏览另一个文件时,它会引发异常。



这是我的ReadCsv类和函数转换为excel和OLEDB连接。



I have a ReadCSv class to read CSV and I pass path through combobox selected or browsed file in function. Initially during load i have a file selected fromcombobox as a default file and when i chnge selected index of combobox and then browse another file,, it throws exception.

Here is my ReadCsv class and function to convert to excel and OLEDB connection.

namespace WindowsFormsApplication4
{
  public static  class ReadCsv
    {
        public static string ReadCSVFile(string csvFilePath)
        {
            string tempFilePath = @"C:\Paras\My Docs\TempCsv.xls";
            Microsoft.Office.Interop.Excel.Application csvReaderApp = null;
            Microsoft.Office.Interop.Excel.Workbook csvReaderWorkBook = null;
            Microsoft.Office.Interop.Excel.Worksheet workSheet = null;
            Microsoft.Office.Interop.Excel.Range range = null;
            try
            {
                csvReaderApp = new Microsoft.Office.Interop.Excel.Application();
                csvReaderWorkBook = csvReaderApp.Workbooks.Add(Type.Missing);
                int[] intColTypes = new int[48];
                for (int index = 0; index < 48; index++)
                {
                    intColTypes[index] = 2;
                }
                workSheet = (Microsoft.Office.Interop.Excel.Worksheet)(csvReaderWorkBook.Worksheets[1]);
                range = (Microsoft.Office.Interop.Excel.Range)(workSheet.get_Range("A1", Type.Missing));
                ImportCSV(csvFilePath, workSheet, range, intColTypes, true);

                csvReaderWorkBook.SaveCopyAs(tempFilePath);
                return tempFilePath;
            }
            catch (COMException comEx)
            {
                return string.Empty;
            }
            finally
            {
                GC.Collect();
                GC.WaitForPendingFinalizers();
                GC.Collect();
                GC.WaitForPendingFinalizers();
                
                Marshal.FinalReleaseComObject(range);
                Marshal.FinalReleaseComObject(workSheet);
                csvReaderWorkBook.Close(false, Type.Missing, Type.Missing);
                Marshal.FinalReleaseComObject(csvReaderWorkBook);
                csvReaderApp.Quit();
                Marshal.FinalReleaseComObject(csvReaderApp);
            }
        }
      
        public static System.Data.DataTable GetData(string strFilePath, string strSheetName)
        {
            OleDbConnection connection = null;
            DataSet dsData = null;
            OleDbDataAdapter da = null;
            var connectionString = string.Format("Provider=Microsoft.ACE.OLEDB.12.0; data source={0}; Extended Properties=Excel 12.0", strFilePath);
            using (connection = new System.Data.OleDb.OleDbConnection(connectionString))
            {
                //Specify Sheet Name to read
                da = new System.Data.OleDb.OleDbDataAdapter("SELECT * FROM [#SHEET_NAME#


。Replace(#SHEET_NAME#,strSheetName),connection);
connection.Open();
dsData = new DataSet();
da.Fill(dsData);
connection.Close();
}
返回dsData.Tables [0];
}

私有静态无效ImportCSV(字符串importFileName,Microsoft.Office.Interop.Excel.Worksheet destinationSheet,
Microsoft.Office.Interop.Excel.Range destinationRange,INT [] columnDataTypes,布尔autoFitColumns)
{
destinationSheet.QueryTables.Add(
TEXT; + Path.GetFullPath(importFileName)
destinationRange,Type.Missing);
destinationSheet.QueryTables [1] .Name = Path.GetFileNameWithoutExtension(importFileName);
destinationSheet.QueryTables [1]。.FieldNames = true;
destinationSheet.QueryTables [1] .RowNumbers = false;
destinationSheet.QueryTables [1] .FillAdjacentFormulas = false;
destinationSheet.QueryTables [1] .PreserveFormatting = true;
destinationSheet.QueryTables [1] .RefreshOnFileOpen = false;
destinationSheet.QueryTables [1] .RefreshStyle = Microsoft.Office.Interop.Excel.XlCellInsertionMode.xlInsertDeleteCells;
destinationSheet.QueryTables [1] .SavePassword = false;
destinationSheet.QueryTables [1] .SaveData = true;
destinationSheet.QueryTables [1] .AdjustColumnWidth = true;
destinationSheet.QueryTables [1] .RefreshPeriod = 0;
destinationSheet.QueryTables [1] .TextFilePromptOnRefresh = false;
destinationSheet.QueryTables [1] .TextFilePlatform = 437;
destinationSheet.QueryTables [1] .TextFileStartRow = 1;
destinationSheet.QueryTables [1] .TextFileParseType = Microsoft.Office.Interop.Excel.XlTextParsingType.xlDelimited;
destinationSheet.QueryTables [1] .TextFileTextQualifier = Microsoft.Office.Interop.Excel.XlTextQualifier.xlTextQualifierDoubleQuote;
destinationSheet.QueryTables [1] .TextFileConsecutiveDelimiter = false;
destinationSheet.QueryTables [1] .TextFileTabDelimiter = false;
destinationSheet.QueryTables [1] .TextFileSemicolonDelimiter = false;
destinationSheet.QueryTables [1] .TextFileCommaDelimiter = true;
destinationSheet.QueryTables [1] .TextFileSpaceDelimiter = false;
destinationSheet.QueryTables [1] .TextFileColumnDataTypes = columnDataTypes;
destinationSheet.QueryTables [1] .Refresh(false);
if(autoFitColumns == true)
destinationSheet.QueryTables [1] .Destination.EntireColumn.AutoFit();
//// cleanup
//this.ActiveSheet.QueryTables [1] .Delete();
}
public static string GetSheetName(string filePath,int sheetIndex)
{
string sheetName = string.Empty;
Microsoft.Office.Interop.Excel.Application excelApp = null;
Microsoft.Office.Interop.Excel.Workbook workBook = null;
Microsoft.Office.Interop.Excel.Sheets sheets = null;
Microsoft.Office.Interop.Excel.Worksheet workSheet = null;
try
{
excelApp = new Microsoft.Office.Interop.Excel.Application();
workBook = excelApp.Workbooks.Add(filePath);
sheets =(Microsoft.Office.Interop.Excel.Sheets)workBook.Worksheets;
workSheet =(Microsoft.Office.Interop.Excel.Worksheet)sheet [sheetIndex];
sheetName = workSheet.Name.ToString();
}
catch(COMException comEx)
{

}
最后
{
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
GC.WaitForPendingFinalizers();
Marshal.FinalReleaseComObject(workSheet);
Marshal.FinalReleaseComObject(sheet);
workBook.Close(false,Type.Missing,Type.Missing);
Marshal.FinalReleaseComObject(workBook);
excelApp.Quit();
Marshal.FinalReleaseComObject(excelApp);
}
返回sheetName;
}
}
}
".Replace("#SHEET_NAME#", strSheetName), connection); connection.Open(); dsData = new DataSet(); da.Fill(dsData); connection.Close(); } return dsData.Tables[0]; } private static void ImportCSV(string importFileName, Microsoft.Office.Interop.Excel.Worksheet destinationSheet, Microsoft.Office.Interop.Excel.Range destinationRange, int[] columnDataTypes, bool autoFitColumns) { destinationSheet.QueryTables.Add( "TEXT;" + Path.GetFullPath(importFileName), destinationRange, Type.Missing); destinationSheet.QueryTables[1].Name = Path.GetFileNameWithoutExtension(importFileName); destinationSheet.QueryTables[1].FieldNames = true; destinationSheet.QueryTables[1].RowNumbers = false; destinationSheet.QueryTables[1].FillAdjacentFormulas = false; destinationSheet.QueryTables[1].PreserveFormatting = true; destinationSheet.QueryTables[1].RefreshOnFileOpen = false; destinationSheet.QueryTables[1].RefreshStyle = Microsoft.Office.Interop.Excel.XlCellInsertionMode.xlInsertDeleteCells; destinationSheet.QueryTables[1].SavePassword = false; destinationSheet.QueryTables[1].SaveData = true; destinationSheet.QueryTables[1].AdjustColumnWidth = true; destinationSheet.QueryTables[1].RefreshPeriod = 0; destinationSheet.QueryTables[1].TextFilePromptOnRefresh = false; destinationSheet.QueryTables[1].TextFilePlatform = 437; destinationSheet.QueryTables[1].TextFileStartRow = 1; destinationSheet.QueryTables[1].TextFileParseType = Microsoft.Office.Interop.Excel.XlTextParsingType.xlDelimited; destinationSheet.QueryTables[1].TextFileTextQualifier = Microsoft.Office.Interop.Excel.XlTextQualifier.xlTextQualifierDoubleQuote; destinationSheet.QueryTables[1].TextFileConsecutiveDelimiter = false; destinationSheet.QueryTables[1].TextFileTabDelimiter = false; destinationSheet.QueryTables[1].TextFileSemicolonDelimiter = false; destinationSheet.QueryTables[1].TextFileCommaDelimiter = true; destinationSheet.QueryTables[1].TextFileSpaceDelimiter = false; destinationSheet.QueryTables[1].TextFileColumnDataTypes = columnDataTypes; destinationSheet.QueryTables[1].Refresh(false); if (autoFitColumns == true) destinationSheet.QueryTables[1].Destination.EntireColumn.AutoFit(); //// cleanup //this.ActiveSheet.QueryTables[1].Delete(); } public static string GetSheetName(string filePath, int sheetIndex) { string sheetName = string.Empty; Microsoft.Office.Interop.Excel.Application excelApp = null; Microsoft.Office.Interop.Excel.Workbook workBook = null; Microsoft.Office.Interop.Excel.Sheets sheets = null; Microsoft.Office.Interop.Excel.Worksheet workSheet = null; try { excelApp = new Microsoft.Office.Interop.Excel.Application(); workBook = excelApp.Workbooks.Add(filePath); sheets = (Microsoft.Office.Interop.Excel.Sheets)workBook.Worksheets; workSheet = (Microsoft.Office.Interop.Excel.Worksheet)sheets[sheetIndex]; sheetName = workSheet.Name.ToString(); } catch (COMException comEx) { } finally { GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); GC.WaitForPendingFinalizers(); Marshal.FinalReleaseComObject(workSheet); Marshal.FinalReleaseComObject(sheets); workBook.Close(false, Type.Missing, Type.Missing); Marshal.FinalReleaseComObject(workBook); excelApp.Quit(); Marshal.FinalReleaseComObject(excelApp); } return sheetName; } } }













这是我的mainform.cs,我有一个组合框,1个文本框显示所选文件的路径,按钮浏览阅读浏览的CSV

//对于openfiledialog的浏览按钮







and this is my mainform.cs where i have a combobox, 1 textbox to display the path of selected file and button browse to read browsed CSV
//For browse button from openfiledialog

  private void Browse_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFile = new OpenFileDialog();
            openFile.Filter = "CSV files (*.csv)|*.csv";
            openFile.Title = "Select Calibration CSV";
            openFile.AutoUpgradeEnabled = false;
                       
            if (openFile.ShowDialog(this) == DialogResult.OK)
            {
                textBox1.Text = openFile.FileName;
            }
            string m_strTempPath = ReadCsv.ReadCSVFile(textBox1.Text);
          string strSheetName = ReadCsv.GetSheetName(m_strTempPath, 1);
          DataTable dt = ReadCsv.GetData(m_strTempPath, strSheetName);
             
                dataGridView1.DataSource = dt;
                     }


//For combobox selected index changed
        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            
            string strPath = comboBox1.SelectedItem.ToString();
            string m_strTempPath = ReadCsv.ReadCSVFile(strPath);
            string strSheetName = ReadCsv.GetSheetName(m_strTempPath, 1);
            DataTable dt = ReadCsv.GetData(m_strTempPath, strSheetName);
            dataGridView1.DataSource = dt;
        }

// to load combobox and read default CSV
        private void Form1_Load(object sender, EventArgs e)
        {
            comboBox1.Items.Add(@"C:\Paras\CSV CALIBRATION.CSV");
            comboBox1.Items.Add(@"C:\Paras\cals_16thOCT2.CSV");
            comboBox1.Items.Add(@"C:\Paras\cals_16thOCT.CSV");
            comboBox1.SelectedIndex = 0;
            string m_strTempPath = ReadCsv.ReadCSVFile(comboBox1.SelectedItem.ToString());
            string strSheetName = ReadCsv.GetSheetName(m_strTempPath, 1);
            DataTable dt = ReadCsv.GetData(m_strTempPath, strSheetName);
            dataGridView1.DataSource = dt;
        }


这篇关于试图读取受保护的内存。这通常表明内存已损坏。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆