5 Replies - 44253 Views - Last Post: 09 March 2009 - 01:17 PM Rate Topic: -----

#1 jsalad08  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 4
  • Joined: 06-March 09

C# Serial Port - UnAuthorizedAccessException

Posted 06 March 2009 - 05:15 PM

Hi, I want to write a simple C# application that reads data from a USB Barcode Reader (attached to COM1). I have been able to get it working using C# SerialPort class, however if the barcode reader is unplugged and plugged in again my system crashes and throws an UnAuthorizedAccessException and from looking at other posts this seems to be a common annoying problem. I am using Win32 register notifications to inform when COM1 is available and when available i try to open it if its not open already this is when the exception is thrown. I have not found a way of catching this exception although trying the app.xml fix which some people suggested on google.

All help is highly appreciated

My code is listed below:


[/b]

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.IO.Ports;
using System.Threading;
using System.Runtime.InteropServices;

namespace ARCBarcodeReader
{
	public partial class Form1 : Form
	{
		string RxString;

		public Form1()
		{
			InitializeComponent();
			RegisterHidNotification();
			try
			{
				if (!serialPort1.IsOpen)
				{
					serialPort1.Open();
					//InitializeComponent();
					txtBarcode.Text = "COM1 is opened succesfully";
				}
			}
			catch (Exception)
			{
				txtBarcode.Text = "Exception caught while trying to open COM1";
			}
			if (SerialPort.GetPortNames().Contains("COM1"))
			{
				try
				{
					if (!serialPort1.IsOpen)
					{
						serialPort1.Open();
						InitializeComponent();
						txtBarcode.Text = "COM1 is opened succesfully";
					}
				}
				catch (Exception)
				{
					txtBarcode.Text = "Exception caught while trying to open COM1";
				}
			}
			else
			{
				txtBarcode.Text = "COM1 not found";
			}
		   
			
		}

		[System.Security.Permissions.PermissionSet(System.Security.Permissions.SecurityAction.Demand, Name = "FullTrust")]
		protected override void WndProc(ref Message m)
		{
			switch (m.Msg)
			{
				case Win32.WM_DEVICECHANGE: OnDeviceChange(ref m); break;
			}
			base.WndProc(ref m);
		}

		void OnDeviceChange(ref Message msg)
		{
			int wParam = (int)msg.WParam;
			if (wParam == Win32.DBT_DEVICEARRIVAL)
			{
				if (SerialPort.GetPortNames().Contains("COM1"))
				{
					try
					{

							txtBarcode.Text = "COM1 is opened succesfully";
							serialPort1.Open();
							InitializeComponent();
					}
					catch (UnauthorizedAccessException)
					{
						txtBarcode.Text = "Exception caught while trying to open COM1";
					}
				}
			}
			else if (wParam == Win32.DBT_DEVICEREMOVECOMPLETE)
			{
			  
				// COM1 disappeared so garbage collect it
				if (!SerialPort.GetPortNames().Contains("COM1"))
				{
					try
					{
						//serialPort1.Close();
						txtBarcode.Text = "Barcode Reader removed";
					}
					catch (Exception e)
					{
						txtBarcode.Text = "Exception: " + e.Message;
					}
					//DriveInfo[] 
				}
				else
				{
					txtBarcode.Text = "Weird, COM1 is still available";
				}
			}

		}

		// Register for USB notifications
		void RegisterHidNotification()
		{
			Win32.DEV_BROADCAST_DEVICEINTERFACE dbi = new
			Win32.DEV_BROADCAST_DEVICEINTERFACE();
		   
			
			int size = Marshal.SizeOf(dbi);
			dbi.dbcc_size = size;
			dbi.dbcc_devicetype = Win32.DBT_DEVTYP_DEVICEINTERFACE;
			dbi.dbcc_reserved = 0;
			dbi.dbcc_classguid = Win32.GUID_DEVINTERFACE_HID;
			dbi.dbcc_name = 0;
			IntPtr buffer = Marshal.AllocHGlobal(size);
			Marshal.StructureToPtr(dbi, buffer, true);
			IntPtr r = Win32.RegisterDeviceNotification(Handle, buffer,
			Win32.DEVICE_NOTIFY_WINDOW_HANDLE);
			if (r == IntPtr.Zero)
				label1.Text = Win32.GetLastError().ToString();
		}

		public void startSystem()
		{
			serialPort1.PortName = "COM1";
			serialPort1.BaudRate = 9600;

			// Try to open the prot
			try
			{
				serialPort1.Open();
			}
			catch (Exception e)
			{
				txtBarcode.Text = "ERROR" + e.Message + " - Please Ensure Barcode Reader is plugged in and restart";

				
			}
			if (serialPort1.IsOpen)
			{
				txtBarcode.ReadOnly = false;
			}
		}

		private void readData(object sender, EventArgs e)
		{
			txtBarcode.AppendText(RxString);

			// We read the length of the barcode
			// use bytes to read
			if (txtBarcode.Text.Length >= 8)
			{

			}
		}

		private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
		{
			RxString = serialPort1.ReadExisting();

			this.Invoke(new EventHandler(readData));
	
		}

	}

	class Win32
	{
		public const int
		WM_DEVICECHANGE = 0x0219;
		public const int
		DBT_DEVICEARRIVAL = 0x8000,
		DBT_DEVICEREMOVECOMPLETE = 0x8004;
		public const int
		DEVICE_NOTIFY_WINDOW_HANDLE = 0,
		DEVICE_NOTIFY_SERVICE_HANDLE = 1;
		public const int
		DBT_DEVTYP_DEVICEINTERFACE = 5;
		public static Guid
		GUID_DEVINTERFACE_HID = new
		Guid("4D1E55B2-F16F-11CF-88CB-001111000030");
	   
		[StructLayout(LayoutKind.Sequential)]
		public class DEV_BROADCAST_DEVICEINTERFACE
		{
			public int dbcc_size;
			public int dbcc_devicetype;
			public int dbcc_reserved;
			public Guid dbcc_classguid;
			public short dbcc_name;
		}

		[DllImport("user32.dll", SetLastError = true)]
		public static extern IntPtr RegisterDeviceNotification(
		IntPtr hRecipient,
		IntPtr NotificationFilter,
		Int32 Flags);

		[DllImport("kernel32.dll")]
		public static extern int GetLastError();
	}
}



[b]

This post has been edited by jsalad08: 06 March 2009 - 05:53 PM


Is This A Good Question/Topic? 0
  • +

Replies To: C# Serial Port - UnAuthorizedAccessException

#2 coden4fun  Icon User is offline

  • if(coden4fun.NotTired){ ContinueToCode(); }
  • member icon

Reputation: 27
  • View blog
  • Posts: 696
  • Joined: 27-February 09

Re: C# Serial Port - UnAuthorizedAccessException

Posted 06 March 2009 - 07:48 PM

View Postjsalad08, on 6 Mar, 2009 - 04:15 PM, said:

Hi, I want to write a simple C# application that reads data from a USB Barcode Reader (attached to COM1). I have been able to get it working using C# SerialPort class, however if the barcode reader is unplugged and plugged in again my system crashes and throws an UnAuthorizedAccessException and from looking at other posts this seems to be a common annoying problem. I am using Win32 register notifications to inform when COM1 is available and when available i try to open it if its not open already this is when the exception is thrown. I have not found a way of catching this exception although trying the app.xml fix which some people suggested on google.

All help is highly appreciated

My code is listed below:


[/b]

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.IO.Ports;
using System.Threading;
using System.Runtime.InteropServices;

namespace ARCBarcodeReader
{
	public partial class Form1 : Form
	{
		string RxString;

		public Form1()
		{
			InitializeComponent();
			RegisterHidNotification();
			try
			{
				if (!serialPort1.IsOpen)
				{
					serialPort1.Open();
					//InitializeComponent();
					txtBarcode.Text = "COM1 is opened succesfully";
				}
			}
			catch (Exception)
			{
				txtBarcode.Text = "Exception caught while trying to open COM1";
			}
			if (SerialPort.GetPortNames().Contains("COM1"))
			{
				try
				{
					if (!serialPort1.IsOpen)
					{
						serialPort1.Open();
						InitializeComponent();
						txtBarcode.Text = "COM1 is opened succesfully";
					}
				}
				catch (Exception)
				{
					txtBarcode.Text = "Exception caught while trying to open COM1";
				}
			}
			else
			{
				txtBarcode.Text = "COM1 not found";
			}
		   
			
		}

		[System.Security.Permissions.PermissionSet(System.Security.Permissions.SecurityAction.Demand, Name = "FullTrust")]
		protected override void WndProc(ref Message m)
		{
			switch (m.Msg)
			{
				case Win32.WM_DEVICECHANGE: OnDeviceChange(ref m); break;
			}
			base.WndProc(ref m);
		}

		void OnDeviceChange(ref Message msg)
		{
			int wParam = (int)msg.WParam;
			if (wParam == Win32.DBT_DEVICEARRIVAL)
			{
				if (SerialPort.GetPortNames().Contains("COM1"))
				{
					try
					{

							txtBarcode.Text = "COM1 is opened succesfully";
							serialPort1.Open();
							InitializeComponent();
					}
					catch (UnauthorizedAccessException)
					{
						txtBarcode.Text = "Exception caught while trying to open COM1";
					}
				}
			}
			else if (wParam == Win32.DBT_DEVICEREMOVECOMPLETE)
			{
			  
				// COM1 disappeared so garbage collect it
				if (!SerialPort.GetPortNames().Contains("COM1"))
				{
					try
					{
						//serialPort1.Close();
						txtBarcode.Text = "Barcode Reader removed";
					}
					catch (Exception e)
					{
						txtBarcode.Text = "Exception: " + e.Message;
					}
					//DriveInfo[] 
				}
				else
				{
					txtBarcode.Text = "Weird, COM1 is still available";
				}
			}

		}

		// Register for USB notifications
		void RegisterHidNotification()
		{
			Win32.DEV_BROADCAST_DEVICEINTERFACE dbi = new
			Win32.DEV_BROADCAST_DEVICEINTERFACE();
		   
			
			int size = Marshal.SizeOf(dbi);
			dbi.dbcc_size = size;
			dbi.dbcc_devicetype = Win32.DBT_DEVTYP_DEVICEINTERFACE;
			dbi.dbcc_reserved = 0;
			dbi.dbcc_classguid = Win32.GUID_DEVINTERFACE_HID;
			dbi.dbcc_name = 0;
			IntPtr buffer = Marshal.AllocHGlobal(size);
			Marshal.StructureToPtr(dbi, buffer, true);
			IntPtr r = Win32.RegisterDeviceNotification(Handle, buffer,
			Win32.DEVICE_NOTIFY_WINDOW_HANDLE);
			if (r == IntPtr.Zero)
				label1.Text = Win32.GetLastError().ToString();
		}

		public void startSystem()
		{
			serialPort1.PortName = "COM1";
			serialPort1.BaudRate = 9600;

			// Try to open the prot
			try
			{
				serialPort1.Open();
			}
			catch (Exception e)
			{
				txtBarcode.Text = "ERROR" + e.Message + " - Please Ensure Barcode Reader is plugged in and restart";

				
			}
			if (serialPort1.IsOpen)
			{
				txtBarcode.ReadOnly = false;
			}
		}

		private void readData(object sender, EventArgs e)
		{
			txtBarcode.AppendText(RxString);

			// We read the length of the barcode
			// use bytes to read
			if (txtBarcode.Text.Length >= 8)
			{

			}
		}

		private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
		{
			RxString = serialPort1.ReadExisting();

			this.Invoke(new EventHandler(readData));
	
		}

	}

	class Win32
	{
		public const int
		WM_DEVICECHANGE = 0x0219;
		public const int
		DBT_DEVICEARRIVAL = 0x8000,
		DBT_DEVICEREMOVECOMPLETE = 0x8004;
		public const int
		DEVICE_NOTIFY_WINDOW_HANDLE = 0,
		DEVICE_NOTIFY_SERVICE_HANDLE = 1;
		public const int
		DBT_DEVTYP_DEVICEINTERFACE = 5;
		public static Guid
		GUID_DEVINTERFACE_HID = new
		Guid("4D1E55B2-F16F-11CF-88CB-001111000030");
	   
		[StructLayout(LayoutKind.Sequential)]
		public class DEV_BROADCAST_DEVICEINTERFACE
		{
			public int dbcc_size;
			public int dbcc_devicetype;
			public int dbcc_reserved;
			public Guid dbcc_classguid;
			public short dbcc_name;
		}

		[DllImport("user32.dll", SetLastError = true)]
		public static extern IntPtr RegisterDeviceNotification(
		IntPtr hRecipient,
		IntPtr NotificationFilter,
		Int32 Flags);

		[DllImport("kernel32.dll")]
		public static extern int GetLastError();
	}
}



[b]


I believe you're getting that error for you're trying to open a COM port that doesn't exist, or is registering as COM1.

For instance, just because you have a device connected to what you believe is COM1 as hardware as in the only COM1 port available doesn't mean that it will register like that in the software. I was working on a microcontroller transferring data through an rs-232 port, and it was the only one connected, but it came up as COM5.

So what you would want to ask yourself is how can I check to see which ports are available and are registered as open, or open on that specific port in the software? You go through all COM ports, and check which ones you have open and add them to a list that you can visually see, so you can later select that specific port and connect to it directly.

I have written a snippet that checks for available ports that are open that can be used, which is the following below.

 #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;
		}



Pass it a combo box, so it can add all available ports, and you can select that specific port name, and when you initialize a SerialPort you can pass it as it's port name doing so should solve this problem.

Hope this helps! ;)
Was This Post Helpful? 0
  • +
  • -

#3 jsalad08  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 4
  • Joined: 06-March 09

Re: C# Serial Port - UnAuthorizedAccessException

Posted 07 March 2009 - 04:10 PM

Hi, thanks allot mate that almost worked, except i get the annoying UnAuthorizedAccessException sometimes. I tried it couple of times and it occurs randomly i am not sure why. Your code would be perfect if there was a way to get rid of this issue. Is there not a way to register to receive notifications from windows when such error occurs so that i can catch it etc i tried adding app.xml as suggested by other people who had similar issues but it didn't work for me. Also i posted my code below and how i used your method isPortOpen just to ensure i did not use it incorrectly. I appreciate your time.

[/b]

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.IO.Ports;
using System.Threading;
using System.Runtime.InteropServices;

namespace ARCBarcodeReader
{
	public partial class Form1 : Form
	{
		string RxString;

		public Form1()
		{
			InitializeComponent();
			RegisterHidNotification();
			if (IsPortOpen(availablePorts))
			{
				if (availablePorts.Items.Contains("COM1"))
				{
					serialPort1.Open();
				}
			}
		}

		[System.Security.Permissions.PermissionSet(System.Security.Permissions.SecurityAction.Demand, Name = "FullTrust")]
		protected override void WndProc(ref Message m)
		{
			switch (m.Msg)
			{
				case Win32.WM_DEVICECHANGE: OnDeviceChange(ref m); break;
			}
			base.WndProc(ref m);
		}

		void OnDeviceChange(ref Message msg)
		{
			int wParam = (int)msg.WParam;
			if (wParam == Win32.DBT_DEVICEARRIVAL)
			{
			   IsPortOpen(availablePorts);

				if (availablePorts.Items.Contains("COM1"))
				{
					txtBarcode.Text = "COM1 available";
					serialPort1.Open();
				}else
				{
					txtBarcode.Text = "COM1 not available";
				}
				
			}
			else if (wParam == Win32.DBT_DEVICEREMOVECOMPLETE)
			{
				IsPortOpen(availablePorts);
			}

		}

		// Register for USB notifications
		void RegisterHidNotification()
		{
			Win32.DEV_BROADCAST_DEVICEINTERFACE dbi = new
			Win32.DEV_BROADCAST_DEVICEINTERFACE();
		   
			
			int size = Marshal.SizeOf(dbi);
			dbi.dbcc_size = size;
			dbi.dbcc_devicetype = Win32.DBT_DEVTYP_DEVICEINTERFACE;
			dbi.dbcc_reserved = 0;
			dbi.dbcc_classguid = Win32.GUID_DEVINTERFACE_HID;
			dbi.dbcc_name = 0;
			IntPtr buffer = Marshal.AllocHGlobal(size);
			Marshal.StructureToPtr(dbi, buffer, true);
			IntPtr r = Win32.RegisterDeviceNotification(Handle, buffer,
			Win32.DEVICE_NOTIFY_WINDOW_HANDLE);
			if (r == IntPtr.Zero)
				label1.Text = Win32.GetLastError().ToString();
		}


		private void readData(object sender, EventArgs e)
		{
			txtBarcode.AppendText(RxString);

			// We read the length of the barcode
			// use bytes to read
			if (txtBarcode.Text.Length >= 8)
			{

			}
		}

		private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
		{
			RxString = serialPort1.ReadExisting();

			this.Invoke(new EventHandler(readData));
	
		}

		//#region[Check Available Ports]
		public bool IsPortOpen(Object obj)
		{
		   
			//create vars for testing
			bool _available = false;
			SerialPort _tempPort;
			((ComboBox)obj).Items.Clear();

			//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(), "Jib: Error - No Ports available", MessageBoxButtons.OK, MessageBoxIcon.Error);
					_available = false;
				}
			}

			//return the temp bool
			return _available;
		}


	}

	class Win32
	{
		public const int
		WM_DEVICECHANGE = 0x0219;
		public const int
		DBT_DEVICEARRIVAL = 0x8000,
		DBT_DEVICEREMOVECOMPLETE = 0x8004;
		public const int
		DEVICE_NOTIFY_WINDOW_HANDLE = 0,
		DEVICE_NOTIFY_SERVICE_HANDLE = 1;
		public const int
		DBT_DEVTYP_DEVICEINTERFACE = 5;
		public static Guid
		GUID_DEVINTERFACE_HID = new
		Guid("4D1E55B2-F16F-11CF-88CB-001111000030");
	   
		[StructLayout(LayoutKind.Sequential)]
		public class DEV_BROADCAST_DEVICEINTERFACE
		{
			public int dbcc_size;
			public int dbcc_devicetype;
			public int dbcc_reserved;
			public Guid dbcc_classguid;
			public short dbcc_name;
		}

		[DllImport("user32.dll", SetLastError = true)]
		public static extern IntPtr RegisterDeviceNotification(
		IntPtr hRecipient,
		IntPtr NotificationFilter,
		Int32 Flags);

		[DllImport("kernel32.dll")]
		public static extern int GetLastError();
	}
}

[b]

Was This Post Helpful? 0
  • +
  • -

#4 coden4fun  Icon User is offline

  • if(coden4fun.NotTired){ ContinueToCode(); }
  • member icon

Reputation: 27
  • View blog
  • Posts: 696
  • Joined: 27-February 09

Re: C# Serial Port - UnAuthorizedAccessException

Posted 07 March 2009 - 06:14 PM

View Postjsalad08, on 7 Mar, 2009 - 03:10 PM, said:

Hi, thanks allot mate that almost worked, except i get the annoying UnAuthorizedAccessException sometimes. I tried it couple of times and it occurs randomly i am not sure why. Your code would be perfect if there was a way to get rid of this issue. Is there not a way to register to receive notifications from windows when such error occurs so that i can catch it etc i tried adding app.xml as suggested by other people who had similar issues but it didn't work for me. Also i posted my code below and how i used your method isPortOpen just to ensure i did not use it incorrectly. I appreciate your time.

[/b]

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.IO.Ports;
using System.Threading;
using System.Runtime.InteropServices;

namespace ARCBarcodeReader
{
	public partial class Form1 : Form
	{
		string RxString;

		public Form1()
		{
			InitializeComponent();
			RegisterHidNotification();
			if (IsPortOpen(availablePorts))
			{
				if (availablePorts.Items.Contains("COM1"))
				{
					serialPort1.Open();
				}
			}
		}

		[System.Security.Permissions.PermissionSet(System.Security.Permissions.SecurityAction.Demand, Name = "FullTrust")]
		protected override void WndProc(ref Message m)
		{
			switch (m.Msg)
			{
				case Win32.WM_DEVICECHANGE: OnDeviceChange(ref m); break;
			}
			base.WndProc(ref m);
		}

		void OnDeviceChange(ref Message msg)
		{
			int wParam = (int)msg.WParam;
			if (wParam == Win32.DBT_DEVICEARRIVAL)
			{
			   IsPortOpen(availablePorts);

				if (availablePorts.Items.Contains("COM1"))
				{
					txtBarcode.Text = "COM1 available";
					serialPort1.Open();
				}else
				{
					txtBarcode.Text = "COM1 not available";
				}
				
			}
			else if (wParam == Win32.DBT_DEVICEREMOVECOMPLETE)
			{
				IsPortOpen(availablePorts);
			}

		}

		// Register for USB notifications
		void RegisterHidNotification()
		{
			Win32.DEV_BROADCAST_DEVICEINTERFACE dbi = new
			Win32.DEV_BROADCAST_DEVICEINTERFACE();
		   
			
			int size = Marshal.SizeOf(dbi);
			dbi.dbcc_size = size;
			dbi.dbcc_devicetype = Win32.DBT_DEVTYP_DEVICEINTERFACE;
			dbi.dbcc_reserved = 0;
			dbi.dbcc_classguid = Win32.GUID_DEVINTERFACE_HID;
			dbi.dbcc_name = 0;
			IntPtr buffer = Marshal.AllocHGlobal(size);
			Marshal.StructureToPtr(dbi, buffer, true);
			IntPtr r = Win32.RegisterDeviceNotification(Handle, buffer,
			Win32.DEVICE_NOTIFY_WINDOW_HANDLE);
			if (r == IntPtr.Zero)
				label1.Text = Win32.GetLastError().ToString();
		}


		private void readData(object sender, EventArgs e)
		{
			txtBarcode.AppendText(RxString);

			// We read the length of the barcode
			// use bytes to read
			if (txtBarcode.Text.Length >= 8)
			{

			}
		}

		private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
		{
			RxString = serialPort1.ReadExisting();

			this.Invoke(new EventHandler(readData));
	
		}

		//#region[Check Available Ports]
		public bool IsPortOpen(Object obj)
		{
		   
			//create vars for testing
			bool _available = false;
			SerialPort _tempPort;
			((ComboBox)obj).Items.Clear();

			//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(), "Jib: Error - No Ports available", MessageBoxButtons.OK, MessageBoxIcon.Error);
					_available = false;
				}
			}

			//return the temp bool
			return _available;
		}


	}

	class Win32
	{
		public const int
		WM_DEVICECHANGE = 0x0219;
		public const int
		DBT_DEVICEARRIVAL = 0x8000,
		DBT_DEVICEREMOVECOMPLETE = 0x8004;
		public const int
		DEVICE_NOTIFY_WINDOW_HANDLE = 0,
		DEVICE_NOTIFY_SERVICE_HANDLE = 1;
		public const int
		DBT_DEVTYP_DEVICEINTERFACE = 5;
		public static Guid
		GUID_DEVINTERFACE_HID = new
		Guid("4D1E55B2-F16F-11CF-88CB-001111000030");
	   
		[StructLayout(LayoutKind.Sequential)]
		public class DEV_BROADCAST_DEVICEINTERFACE
		{
			public int dbcc_size;
			public int dbcc_devicetype;
			public int dbcc_reserved;
			public Guid dbcc_classguid;
			public short dbcc_name;
		}

		[DllImport("user32.dll", SetLastError = true)]
		public static extern IntPtr RegisterDeviceNotification(
		IntPtr hRecipient,
		IntPtr NotificationFilter,
		Int32 Flags);

		[DllImport("kernel32.dll")]
		public static extern int GetLastError();
	}
}

[b]


Evertime I hear UnAuthroized, protected levels of hardware software I think vista. By chance could you be running vista?

That code works perfectly in XP, and I haven't had any problems with that code at all.
Was This Post Helpful? 0
  • +
  • -

#5 jsalad08  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 4
  • Joined: 06-March 09

Re: C# Serial Port - UnAuthorizedAccessException

Posted 08 March 2009 - 10:05 AM

Hi, no am not using Windows Vista i am using Windows XP Professional. The error does not occur the first time i run the above isPortOpen code, However as you can see from my code whenever a usb device is plugged in i use the IsPortOpen to check if COM1 is still there and then if so and if its not open i try to open it, this is when the UnAuthorizedAccessExceptipion occurs and the application crashes.
Was This Post Helpful? 0
  • +
  • -

#6 jsalad08  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 4
  • Joined: 06-March 09

Re: C# Serial Port - UnAuthorizedAccessException

Posted 09 March 2009 - 01:17 PM

View Postjsalad08, on 8 Mar, 2009 - 09:05 AM, said:

Hi, no am not using Windows Vista i am using Windows XP Professional. The error does not occur the first time i run the above isPortOpen code, However as you can see from my code whenever a usb device is plugged in i use the IsPortOpen to check if COM1 is still there and then if so and if its not open i try to open it, this is when the UnAuthorizedAccessExceptipion occurs and the application crashes.


maybe someone more sensible than myself can notice something wrong with my code which would cause such an UnAuthorizedAccessException?
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1