Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations derfloh on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

UnauthorizedAccessException serialport

Status
Not open for further replies.

kirkhettfield

Programmer
Joined
Apr 21, 2009
Messages
3
Location
BE
Hi, I have a problem with the UnauthorizedAccessException. Every time I
unplug=>plug my USB device, I get this exception. The problem is
that the exception is random so I cant track the source of it.

I can catch the exception, but it doesn't help because the program immediately shuts down.
CODE

public SerialPort moPort = new SerialPort();
public System.Timers.Timer timer6 = new System.Timers.Timer(1000);



void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
}

void moPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
delstring2 invoke_del = new delstring2(invoke_function);
try
{
this.Invoke(invoke_del, moPort.ReadLine());
kijken_gps_uitgetrokken = false;
}
catch
{
Longitude = "0";
kmperuur = 0;
direction = "0";
kwaliteit_signaal = "0";
kijken_gps_uitgetrokken = true;
}
}

public bool IsPortOpen()
{
//create vars for testing
bool _available = false;

//create a loop for each string in SerialPort.GetPortNames
foreach (string str in SerialPort.GetPortNames())
{
if (str == "COM3")
{
_available = true;
}
}

//return the temp bool
// Console.WriteLine("available " + _available);
return _available;
}

private void button1_Click(object sender, EventArgs e)
{
if (moPort.IsOpen == true)
{
moPort.DiscardInBuffer();
try
{
moPort.Close();
}
catch { }
button1.Text = "Connect";
comboBox1.Enabled = true;
textBox4.Enabled = true;
Console.WriteLine("timer1 gestopt");
}
else
{
moPort.PortName = "COM3";
moPort.BaudRate = 4800;
moPort.StopBits = System.IO.Ports.StopBits.One; //1
moPort.DataBits = 8;
moPort.Parity = System.IO.Ports.Parity.None;
try { moPort.Open(); }
catch { }
button1.Text = "Disconnect";
comboBox1.Enabled = false;
textBox4.Enabled = false;
timer6.Start();
}
}

void timer6_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
bool temp = IsPortOpen();
if (temp == false)
{
Console.WriteLine("com3 niet aanwezig");
try
{
moPort = null;
Console.WriteLine("Com poort disposed");
}
catch { }
else
{
try
{
Console.WriteLine("Com3 aanwezig");
moPort = new SerialPort();
moPort.PortName = "COM3";
moPort.BaudRate = 4800;
moPort.StopBits = System.IO.Ports.StopBits.One; //1
moPort.DataBits = 8;
moPort.Parity = System.IO.Ports.Parity.None;
moPort.Open();
Console.WriteLine("Com poort geopend");
}
catch { }
}
}
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top