views:

96

answers:

3

Hi, im trying to write a string to a COM4 which is a usb-serial adapter using Visual Studio C# and got the following error:

Access to the port 'COM4' is denied.

My program is extremely simple:

serialport.Open();
serialport.WriteLine("test");
serialport.Close();

I also tried using pyserial with python and got:

Traceback (most recent call last):
  File "<pyshell#2>", line 1, in <module>
    ser.write("string")
  File "C:\Python27\lib\site-packages\serial\serialwin32.py", line 255, in write
    raise SerialException("WriteFile failed (%s)" % ctypes.WinError())
SerialException: WriteFile failed ([Error 6] The handle is invalid.)

I know this question isn't really related to programming and is probably a Windows 7 thing but I was hoping someone has already had a similar problem.

+1  A: 

Try this:

Right click on your executable and choose "run as administrator". Windows 7 by default runs programs without admin privileges. I'm betting that the ability to write to a COM port requires running a program as an Administrator.

Turtle
@Turtle i tried your suggestion but it doesn't seem to work
Pandiya Chendur
Did you try restarting your computer? Seriously, unplugging the device might screw things up, and this would fix that. Take a look at http://social.msdn.microsoft.com/Forums/en-US/vcgeneral/thread/49e8839e-e833-498d-a3a1-28922ec7bf43
Turtle
@Turtle The problem is I won't be able to to this for a python script. Haven't tried yet with the exe file.
kirbuchi
@Turtle ya i didnt restart it. Ok i ll let you know once i do that
Pandiya Chendur
It doesn't have anything to do with permissions, the port is simply in use by another process.
Hans Passant
+1  A: 

You cannot have multiple simultaneous connections to a serial port. The port is likely in use.

Ed Swangren
+1, this is the reason.
Hans Passant
A: 

It had nothing to do with permissions neither with the port being in use. I found a related question which said it was because of the version I had installed (64 bit Python and 32 bit pyserial) I feel so silly.

What I still can't figure out is why it also didn't work on C# but that's OK. I'll just use python.

kirbuchi