csharp 调用kepware进行读写的示例
时间: 2023-10-11 19:11:33 浏览: 56
C# 调用 Kepware 进行读写的示例代码如下:
```csharp
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using OPCAutomation;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
OPCServer KepServer = new OPCServer();
try
{
object se = KepServer.GetOPCServers("localhost");
Console.WriteLine("KEPServer列表:");
foreach (string item in (Array)se)
{
Console.WriteLine(item.ToString());
}
Console.WriteLine("请输入服务器名:");
string sKepServer = Console.ReadLine();
bool conn = KepServer.Connect(sKepServer, "");
if (conn)
{
Console.WriteLine("连接成功!");
OPCGroups KepGroups = KepServer.OPCGroups;
OPCGroup KepGroup = KepGroups.Add("KepwareGroup");
KepGroup.UpdateRate = 250;
KepGroup.IsActive = true;
KepGroup.IsSubscribed = true;
OPCItems KepItems = KepGroup.OPCItems;
OPCItem KepItem = KepItems.AddItem("Random.String");
Console.WriteLine("随机字符串值:" + KepItem.Value.ToString());
Console.ReadKey();
// 读取数据
Array arr;
object err;
int iUpdateRate = KepGroup.UpdateRate;
while (true)
{
KepGroup.AsyncRead(KepItems.Count, KepItems, out arr, out err, iUpdateRate, 0);
for (int i = 1; i <= KepItems.Count; i++)
{
Console.WriteLine(KepItems.Item(i).ItemID + ":" + arr.GetValue(i) + " 错误码:" + err.ToString());
}
Console.WriteLine("请输入要写入的字符串值:");
string sValue = Console.ReadLine();
KepItem.Write(sValue);
}
}
else
{
Console.WriteLine("连接失败!");
Console.ReadKey();
}
KepServer.Disconnect();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Console.ReadKey();
}
}
}
}
```
此示例代码在前面的示例代码基础上增加了读取数据和写入数据的部分。需要注意的是,写入数据时需要根据实际情况修改对应的 OPCItem 名称和写入值。