Hello,
I´m having problem
with get access to my Serial Ports using C#.
I’m using Visual Studio 2005 and Vista.
I’ve
checked that the Serial Port is “COM1”, so this shouldn’t be the problem.
Error
message: “System.UnauthorizedAccessException ”.
I’ve
googled this and it seems to be some security problems, maybe with Vista.
The Code:
(using System.IO.Ports;)
public partial class Arduino : System.Web.UI.Page
{
SerialPort sp = new
SerialPort("COM1",
9600, Parity.None, 8, StopBits.One);
protected void
Page_Load(object sender, EventArgs e)
{
}
protected void
Button1_Click(object sender, EventArgs e)
{
sp.Open();
TextBox1.Text =
"" + sp.ReadByte();
sp.Close();
}
Anyone have
experience from this?
vivek kulkarniPosted Mar 18, 2009, 2:55 AM
hi,
you need to check if the com port is open before using it.
here is a code that will help u.
#region[Check Available Ports]
public bool IsPortOpen(Object obj)
{
//create vars for testing
bool _available = false;
SerialPort _tempPort;
//create a loop for each string in SerialPort.GetPortNames
foreach (string str in SerialPort.GetPortNames())
{
try
{
_tempPort = new SerialPort(str);
_tempPort.Open();
//if the port exist and we can open it
if (_tempPort.IsOpen)
{
((ComboBox)obj).Items.Add(str);
_tempPort.Close();
_available = true;
}
}
//else we have no ports or can't open them display the
//precise error of why we either don't have ports or can't open them
catch (Exception ex)
{
MessageBox.Show(ex.ToString(), "Error - No Ports available", MessageBoxButtons.OK, MessageBoxIcon.Error);
_available = false;
}
}
//return the temp bool
return _available;
}