一次又一次地得到这个错误 [英] getting this error again and again
问题描述
An exception of type 'System.Runtime.InteropServices.COMException' occurred in mscorlib.dll but was not handled in user code
Additional information: Exception from HRESULT: 0x800A03EC
If there is a handler for this exception, the program may be safely continued.
here is my code what i am using.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
using System.Windows.Forms;
using Excel = Microsoft.Office.Interop.Excel;
using System.IO.Ports;
using System.IO;
namespace WindowsFormsApplication7
{
public partial class Form1 : Form
{
private SerialPort myport;
private string in_data, time;
private string j, l;
public int i=1, k, time_sec,count=0;
private DateTime datetime;
public string key, add_data, data, filename,filename1, pathfile, rxd_no, date, ravi1;
public string[] arr = new string[60];
public string[] arr1 = new string[60];
float ravi;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
string name = Environment.UserName;
date = DateTime.Today.ToShortDateString(); // get the current date
pathfile = @"C:\Users\" + name + "\\Documents\\";
// pathfile = @"C:\Users\BADLIA\Documents\";
filename = DateTime.Now.ToString("yyyyMMdd") + ".xls";
filename1 = "directory"+DateTime.Now.ToString("yyyyMMdd")+".xls";// file name = current date
// file name = current date
if (File.Exists(pathfile + filename) == true)
{ }
else
{
File.CreateText(pathfile + filename).Close();
Excel._Application xlApp; // TO access excel file
Excel.Workbook xlWorkBook;
Excel.Worksheet xlWorkSheet;
object misValue = System.Reflection.Missing.Value;
xlApp = new Excel.Application(); // start new excel application
xlApp.DisplayAlerts = false; // off display alerts
xlWorkBook = xlApp.Workbooks.Open(pathfile + filename, 0, false, 5, "", "", false, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "", true, false, 0, true, false, false);
// open file in write mode
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
//get_Item(1) == sheet1
xlWorkSheet.Cells[1, 1] = "time"; // cells[row,column]
xlWorkSheet.Cells[1, 2] = "weight";
//xlWorkSheet.Cells[i, 3] = data;
// Excel.Range chartRange;
Excel.ChartObjects xlCharts = (Excel.ChartObjects)xlWorkSheet.ChartObjects(Type.Missing);
//Excel.ChartObject myChart1 = (Excel.ChartObject)xlCharts.Delete();
Excel.ChartObject myChart = (Excel.ChartObject)xlCharts.Add(10, 80, 300, 250);
Excel.Chart chartPage = myChart.Chart;
//chartRange = xlWorkSheet.get_Range("A1", "B" + i);
//chartPage.SetSourceData(chartRange, misValue);
//chartPage.ChartType = Excel.XlChartType.xlColumnStacked100;
xlWorkBook.SaveAs(pathfile + filename, Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
xlWorkBook.Close(true, misValue, misValue); //true== to save changes
xlApp.Quit();
releaseObject(xlWorkSheet);
releaseObject(xlWorkBook);
releaseObject(xlApp);
}
if (File.Exists(pathfile + filename1) == true)
{
Excel._Application xlApp; // TO access excel file
Excel.Workbook xlWorkBook;
Excel.Worksheet xlWorkSheet;
object misValue = System.Reflection.Missing.Value;
xlApp = new Excel.Application(); // start new excel application
xlApp.DisplayAlerts = false; // off display alerts
xlWorkBook = xlApp.Workbooks.Open(pathfile + filename1, 0, false, 5, "", "", false, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "", true, false, 0, true, false, false);
// open file in write mode
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);//get_Item(1) == sheet1
key = xlWorkSheet.get_Range("A1", "A1").Value2.ToString();
int.TryParse(key, out i);
MessageBox.Show(key);
xlWorkBook.SaveAs(pathfile + filename1, Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
xlWorkBook.Close(true, misValue, misValue); //true== to save changes
xlApp.Quit();
releaseObject(xlWorkSheet);
releaseObject(xlWorkBook);
releaseObject(xlApp);
}
else
{
File.CreateText(pathfile + filename1).Close();
}
}
private void button2_Click(object sender, EventArgs e)
{
if (count == 0)
{
count++;
string name = Environment.MachineName;
System.Diagnostics.Process[] process = System.Diagnostics.Process.GetProcessesByName("Excel");
foreach (System.Diagnostics.Process p in process)
{
if (!string.IsNullOrEmpty(p.ProcessName))
{
try
{
p.Kill();
}
catch { }
}
}
myport = new SerialPort(); // define new serial port
myport.BaudRate = 9600; // set baudrate of new serial port
myport.PortName = port_name.Text; // gets the name of the port which is written in textbox named "port_name"
myport.Parity = Parity.None;
myport.DataBits = 8;
myport.StopBits = StopBits.One;
port_name.Visible = true;
// Serial write
time = datetime.Hour + ":" + datetime.Minute + ":" + datetime.Second;
myport.DataReceived += myport_DataReceived;
try
{
myport.Open(); // start serial port
myport.WriteLine("start"); // Serial write
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error"); // displays"error" when exception occurs
}
this.Invoke(new EventHandler(Excel_start));
}
}
void myport_DataReceived(object sender, SerialDataReceivedEventArgs e) // predefined funtion name " <portname>_Datareceived"
{
//this function is called automatically whenever data is received on serial port
// rxd_no = myport.ReadLine(); // "readline" read upto new line
in_data = myport.ReadLine();
// data = myport.ReadTo("\x03");// read upto new line
time_sec = DateTime.Now.Second; // get the current second
j = in_data;
// ravi = Convert.ToSingle(in_data);
float.TryParse(in_data, out ravi);
l = data;
k = time_sec;
arr[k] = j;
arr1[k] = l;
this.Invoke(new EventHandler(displaydata_event));
}
private void displaydata_event(object sender, EventArgs e)
{
datetime = DateTime.Now; // define variable
// string time = datetime.Hour + ":" + datetime.Minute + ":" + datetime.Second;
try
{
int time_sec = DateTime.Now.Second; // get the current minute
k = time_sec;
chart1.Series["Weight"].Points.AddXY(time, j);
}
catch (Exception ex4)
{
MessageBox.Show(ex4.Message, "Error");
}
weight.Text = j;
}
private void button3_Click(object sender, EventArgs e)
{
try
{
count = 0;
myport.Close(); // close communication
}
catch (Exception ex2)
{
MessageBox.Show(ex2.Message, "Error");
}
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
// Thread.Sleep(3000);
while (myport.IsOpen == true)
{
Excel._Application xlApp; // TO access excel file
Excel.Workbook xlWorkBook;
Excel.Worksheet xlWorkSheet;
object misValue = System.Reflection.Missing.Value;
xlApp = new Excel.Application(); // start new excel application
xlApp.DisplayAlerts = false; // off display alerts
xlWorkBook = xlApp.Workbooks.Open(pathfile + filename, 0, false, 5, "", "", false, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "", true, false, 0, true, false, false);
// open file in write mode
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
xlWorkSheet.Cells[i, 1] = time; // cells[row,column]
xlWorkSheet.Cells[i, 3] = ravi;
//xlWorkSheet.Cells[i, 3] = data;
i++;
Excel.Range chartRange;
Excel.ChartObjects xlCharts = (Excel.ChartObjects)xlWorkSheet.ChartObjects(Type.Missing);
Excel.ChartObject myChart1 = (Excel.ChartObject)xlCharts.Delete();
Excel.ChartObject myChart = (Excel.ChartObject)xlCharts.Add(10, 80, 300, 250);
Excel.Chart chartPage = myChart.Chart;
chartRange = xlWorkSheet.get_Range("A2", "B" + i);
chartPage.SetSourceData(chartRange, misValue);
chartPage.ChartType = Excel.XlChartType.xlLine;
xlWorkBook.SaveAs(pathfile + filename, Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
xlWorkBook.Close(true, misValue, misValue); //true== to save changes
xlApp.Quit();
releaseObject(xlWorkSheet);
releaseObject(xlWorkBook);
releaseObject(xlApp);
xlApp = new Excel.Application(); // start new excel application
xlApp.DisplayAlerts = false; // off display alerts
xlWorkBook = xlApp.Workbooks.Open(pathfile + filename1, 0, false, 5, "", "", false, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "", true, false, 0, true, false, false);
// open file in write mode
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
//get_Item(1) == sheet1
xlWorkSheet.Cells[1, 1] = i; // cells[row,column]
xlWorkBook.SaveAs(pathfile + filename1, Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
xlWorkBook.Close(true, misValue, misValue); //true== to save changes
xlApp.Quit();
releaseObject(xlWorkSheet);
releaseObject(xlWorkBook);
releaseObject(xlApp);
if (backgroundWorker1.CancellationPending)//checks for cancel request
{
e.Cancel = true;
break;
}
}
}
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
}
private void Excel_start(object sender, EventArgs e)
{
backgroundWorker1.RunWorkerAsync();
}
private void releaseObject(object obj)
{
try
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
obj = null;
}
catch (Exception ex)
{
obj = null;
MessageBox.Show("Unable to release the Object " + ex.ToString());
}
finally
{
GC.Collect();
}
}
private void button4_Click(object sender, EventArgs e)
{
try
{
this.Invoke(new EventHandler(button3_Click));
backgroundWorker1.CancelAsync();//makes the backgroundworker stop
Excel.Application xlApp;
Excel.Workbook xlWorkBook;
Excel.Worksheet xlWorkSheet;
object misValue = System.Reflection.Missing.Value;
xlApp = new Excel.Application(); // start new excel application
xlApp.DisplayAlerts = false; // off display alerts
xlWorkBook = xlApp.Workbooks.Open(pathfile + filename, 0, false, 5, "", "", false, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "", true, false, 0, true, false, false);
// open file in write mode
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
//xlWorkBook.SaveAs("csharp.net-informations.xls", Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
xlWorkBook.Save();
xlApp.Visible = true;
xlApp .UserControl = true;
// xlWorkBook.Close(true, misValue, misValue);
// xlApp.Quit();
//releaseObject(xlWorkSheet);
//releaseObject(xlWorkBook);
//releaseObject(xlApp);
}
catch
{
}
}
}
}
< b>
推荐答案
我们无法从这一块代码告诉你。
第一件事要做的是找出创建异常的地方:并且假装异常并假装他们没有做到这一点并没有帮助那里:
We can't tell you from that lump of code.
The first thing to do is find out where the exception is being created: and swollowing exceptions and pretending they didn;t happen isn't helping there:
private void button4_Click(object sender, EventArgs e)
{
try
{
...
}
catch
{
}
}
这并不能解决任何问题,只是意味着你的应用因此不会立即崩溃。获取Exception对象并检查它,记录它,报告它:几乎任何东西都比吞下它并希望更好!
所以改变你的尝试... catch
为您提供信息,并在调试器中运行它以找出生成异常的位置。这应该让你知道在你的代码中你做错了什么导致外部代码检测到问题。
但没有它,所有人都可以做的就是猜...
That doesn;t cure any problems, it just means that your app doesn't crash immediately as a result. Get the Exception object and examine it, log it, report it: almost anything is better than just swallowing it and hoping!
So change your try...catch
to give you information, and run it in the debugger to find out where the exception is generated. That should give you an idea where in your code you are doing something wrong that causes the external code to detect a problem.
But without that, all anyone can do is guess...
这篇关于一次又一次地得到这个错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!