Alfred Dominic

Alfred Dominic

  • NA
  • 1
  • 5.8k

Serial Port communication in C#

Oct 3 2013 12:05 PM
I am trying to start with serial port communication using C# for my project. So even though i am familiar with the C# language i am new into I/O Port communication and i seem to be having some problem with my code
 
using System;
using System.IO.Ports;
 
class Program
{
	public static void Main ()
	{
		string portName = @"\\.\COM10";
		_serialPort = new SerialPort (portName);
		_serialPort.Close ();
	}
}
 

i am getting an error :
Error	1	The name '_serialPort' does not exist in the current context	c:\users\alfie\documents\visual studio 2012\Projects\serial\serial\Serial_port.cs
 

Someone pls help me get started with this. . 
 
Also i have tested with the following code and verified that the COM10 port is working and is of type "char"
 
class Program
{
    static void Main (string[] args)
    {
        string portName = @"\\.\COM10";
        IntPtr handle = CreateFile (portName, 0, 0, IntPtr.Zero, 3, 0x80, IntPtr.Zero);
        if(handle == (IntPtr) (-1))
        {
            Console.WriteLine ("Could not open " + portName + ": " + new Win32Exception ().Message);
            Console.ReadKey ();
            return;
        }
 
        FileType type = GetFileType (handle);
        Console.WriteLine ("File " + portName + " reports its type as: " + type);
 
        Console.ReadKey ();
    }
 
    [DllImport ("kernel32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall, SetLastError = true)]
    public static extern IntPtr CreateFile (string lpFileName, uint dwDesiredAccess, uint dwShareMode, IntPtr SecurityAttributes, uint dwCreationDisposition, uint dwFlagsAndAttributes, IntPtr hTemplateFile);
 
    [DllImport ("kernel32.dll")]
    static extern FileType GetFileType (IntPtr hFile);
 
    enum FileType : uint
    {
        UNKNOWN = 0x0000,
        DISK = 0x0001,
        CHAR = 0x0002,
        PIPE = 0x0003,
        REMOTE = 0x8000,
    }
}

Answers (1)