Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

C# and serial port access

Status
Not open for further replies.

Guest_imported

New member
Jan 1, 1970
0
0
0
How can I access the serial ports with C#?

I've tried opening the filestream class with no luck.

There is a create file method under the Microsoft.Win32 namespace but i'ts a private method of nativecalls.

I don't want to create an object with C++ for serial IO.

 
jonelf,

I checked your link, and it no longer exist. I was wondering if you by chance have a copy of the code from that link that you can post. I can not find anything on C# and Serial I/O
 
This can be easily by using the CreateFile method found in kernel32.dll however it seems as though you want to do it in VB.NET and I am not sure if unsafe code sections are allowed in VB.NET. Here is the C# code though.

using System.Runtime.InteropServices;

put this next part as a member in your class


[DllImport("kernel32", SetLastError=true)]
static extern unsafe int CreateFile(
string filename,
uint desiredAccess,
uint shareMode,
uint attributes, // really SecurityAttributes pointer
uint creationDisposition,
uint flagsAndAttributes,
uint templateFile);

const uint GENERIC_READ = 0x80000000;
const uint OPEN_EXISTING = 3;


int handle = CreateFile("COM1", GENERIC_READ, 0, 0, OPEN_EXISTING, 0, 0);

if(handle != -1)
{
FileStream myStream = new FileStream(new IntPtr(handle), FileAccess.ReadWrite, true);
//do stuff with the port
}

Hope this helps you out!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top