I'm trying to read and write to a usb modem that is using the com port 3 with this code.
SerialPort sp = new SerialPort();
sp.PortName = "COM3";
//sp.DataReceived += new SerialDataReceivedEventHandler(sp_DataReceived);
sp.Open();
sp.Write("AT<CR>");
byte[] bytes = new byte[sp.BytesToRead];
sp.Read(bytes, 0, sp.BytesToRead);
textBox1.Text = Encoding.UTF8.GetString(bytes);
But I get this error :
Access to the port 'COM3' is denied.
Someone have an idea ...
Thanks
You can only open the port once. Maybe you're accidentally opening it more than once within your code or another program is using it?
Related
I am doing a project of Modbus SCADA using easymodbus library in c#.
In application, sometimes communication gets disconnected and then when I retry to do modbus connection I get error Access to port 'COM3' denied or else Access to serial port denied.
Here is Modbus connection code
ModbusClient modbusClient = new ModbusClient("COM3");
modbusClient.Baudrate = 115200;
modbusClient.Parity = System.IO.Ports.Parity.None;
modbusClient.StopBits = System.IO.Ports.StopBits.One;
modbusClient.ConnectionTimeout = 1000;
if (!modbusClient.Connected)
{
modbusClient.Connect();
}
what do they mean about
port.DtrEnable = true,
https://support.cognex.com/docs/dmst_616SR1/web/EN/Comms_Prog_Manual/Content/Topics/PDF/DMCAP/DMCCApplicationDevelopment.htm
Where do I put this code on the sample code?
You are probably working with COM ports.
you need import
using System.IO.Ports;
And when you create a SerialPort you should set the property
var serialPort = new SerialPort();
serialPort.DtrEnable = true;
I have a private function that creates a new serial port and opens it. From time to time, I get the "Safe handle has been closed" exception, that terminates the application. Now, I've been reading a few optional fixes and would like to know from your experience, what may be the real problem in my code.
1) Need to define the _serialPort variable outside of the scope of this private function.
2) The serial port's readTimeout property should not be infinite.
3) The using statement above disposes my portName variable.
SerialPort _serialPort;
string[] devices =
ConfigurationManager.AppSettings["GasAnalyzerDeviceName"].Split(',');
string portName;
using (var searcher = new ManagementObjectSearcher("SELECT * FROM Win32_PnPEntity"))
{
portName = (from p in searcher.Get().Cast<ManagementBaseObject>()
let c = "" + p["Caption"]
where c != null
where devices.Any(d => c.Contains(d.Trim()))
from pn in SerialPort.GetPortNames()
where c.Contains(pn)
select pn).FirstOrDefault();
}
if (portName == null)
portName = ConfigurationManager.AppSettings["GasAnalyzerPortName"];
if (portName == null)
throw new Exception("Gas port not found");
// Create a new SerialPort object with default settings.
_serialPort = new SerialPort();
// Set Serial port properties
_serialPort.PortName = portName;
_serialPort.BaudRate = 115200;
_serialPort.DataBits = 8;
_serialPort.Parity = Parity.None;
_serialPort.StopBits = StopBits.One;
_serialPort.Handshake = Handshake.None;
_serialPort.ReadTimeout = Timeout.Infinite;//1200;
_serialPort.WriteTimeout = 1200;
Thanks!
I think you can discard options 2) and 3).
Number one is a possible candidate, but there is not enough code to be sure: If there are no other references to your SerialPort it becomes a candidate for garbage collection. Once it is garbage collected, any attempt to access it will result in an exception, tough I would expect a NullReferenceException.
There can be another cause: if your serial port is emulated over e.g. a USB device, and that device gets removed while your application is running, the underlying connection will be disposed.
When you try to use the SerialPort in your application after that has happened, you will get the 'safe handle has been closed' exception.
I am using microcontroller to send data to computer. This is the code that I am using to get data:
serialPort1.PortName = "COM13";
serialPort1.BaudRate = 57600;
serialPort1.DataBits = 8;
serialPort1.Parity = Parity.Odd;
serialPort1.StopBits = StopBits.One;
serialPort1.Open();
private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
SerialPort sp = (SerialPort)sender;
output += sp.ReadByte() + " ";
}
But the problem is that I am getting wrong data, even sometimes I am missing one bytes. I am using "terminal" and it seems that I am sending data correctly with microcontroller but with c# I am getting wrong data.
Also is there any way to get the parameter of serial port automatically so that I dont need to set the parameters my self.
This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
Listening to Port 5060
I am developing a SIP client.And I have a question.
I want listen 5060 port for catch the SIP Server Message.For this,I coding something.(Also I take admin rights in program)
But I get SocketException: "An attempt was made to access a socket in a way forbidden by its access permissions" (Native error code: 10013)...
My Code:
private void ListenPort() {
WindowsPrincipal pricipal = new WindowsPrincipal(WindowsIdentity.GetCurrent());
bool hasAdministrativeRight = pricipal.IsInRole(WindowsBuiltInRole.Administrator);
TcpListener server = null;
Int32 port = 5060;
IPAddress localAddr = IPAddress.Parse("192.168.1.33");
server = new TcpListener(localAddr, port);
Byte[] bytes = new Byte[1000];
String data = null;
while (hasAdministrativeRight == true)
{
server.Start();
int i = 0;
while (1==1)
{
TcpClient client = server.AcceptTcpClient();
NetworkStream stream = client.GetStream();
data = null;
i = stream.Read(bytes, 0, bytes.Length);
data += System.Text.Encoding.ASCII.GetString(bytes, 0, i);
label3.Text += data;
this.Refresh();
Thread.Sleep(500);
}
}
}
Where do you think the problem?
Have you checked that no other program is already using port 5060? That's what this error can mean.
See this discussion on the matter: http://social.msdn.microsoft.com/Forums/en-US/netfxnetcom/thread/d23d471c-002a-4958-829e-eb221c8a4b76/
You need to call server.Start() outside the while loop and before the first AcceptTcpClient call.
Also try using IPAddress.Any instead of IPAddress.Parse("192.168.1.33") for your listener ip
Make sure any other SIP Server program not installed as a Windows service which has using according port.
Type in netstat -an and it will show you the “listening” ports or try to googling port check softwares.
And check your SIP Server configuration for is it running over TCP or UDP.