您的位置:首页 > 其它

SnmpSharpNet OctetString DateAndTime自定义解析

2016-06-01 09:25 351 查看
在进行有关Snmpsharpnet的变成时遇到一个问题,当OctetString向时间转换时产生的是乱码。是因为snmpsharpnet并没有定义OctetString向datetime转换的函数。经过笔者的学习与实践找到了解决的办法。接下来以获得计算机上已安装程序的安装时间为例:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using SnmpSharpNet;//需要添加引用
namespace 时间乱码问题
{
class Program
{
static void Main(string[] args)
{
SimpleSnmp snmp = new SimpleSnmp("127.0.0.1", "public");

if (!snmp.Valid)
{

return;
}
Dictionary<Oid, AsnType> result = snmp.Walk(SnmpVersion.Ver2, ".1.3.6.1.2.1.25.6.3.1.5");//程序安装时间

if (result == null)
{

return;
}

foreach (KeyValuePair<Oid, AsnType> kvp in result)
{
//Console.WriteLine(kvp.Value.ToString()); //如果是执行这一句就会发现是乱码结果
Console.WriteLine(parseDateAndTimeOctet((OctetString)kvp.Value));
}
}
public static String parseDateAndTimeOctet( OctetString v )
{

//OctetString

byte[] bts = v.ToArray();

byte[] format_str = new byte[128]; //保存格式化过后的时间字符串

int year;

int month;

int day;

int hour;

int minute;

int second;

//int msecond;
year =year = bts[0] * 256 + bts[1];
month = bts[2];
day = bts[3];
hour = bts[4];
minute = bts[5];
second = bts[6];
//msecond = bts[7];
//以下为格式化字符串
int index = 3;
int temp = year;

for (; index >= 0; index--)
{
format_str[index] = (byte)(48 + (temp - temp / 10 * 10));
temp /= 10;
}

format_str[4] = (Byte)'-';
index = 6;
temp = month;
for (; index >= 5; index--)
{
format_str[index] = (byte)(48 + (temp - temp / 10 * 10));
temp /= 10;
}

format_str[7] = (Byte)'-';
index = 9;
temp = day;
for (; index >= 8; index--)
{

format_str[index] = (byte)(48 + (temp - temp / 10 * 10));

temp /= 10;

}
format_str[10] = (Byte)' ';
index = 12;
temp = hour;
for (; index >= 11; index--)
{
format_str[index] = (byte)(48 + (temp - temp / 10 * 10));
temp /= 10;
}

format_str[13] = (Byte)':';
index = 15;
temp = minute;
for (; index >= 14; index--)
{

format_str[index] = (byte)(48 + (temp - temp / 10 * 10));

temp /= 10;

}

format_str[16] = (Byte)':';
index = 18;
temp = second;
for (; index >= 17; index--)
{
format_str[index] = (byte)(48 + (temp - temp / 10 * 10));

temp /= 10;

}

//int i = 6;
//while (i >= 0)
//{
// Console.WriteLine("{0}", bts[i]);
// i--;
//}

return System.Text.Encoding.Default.GetString(format_str);// new String(format_str);

}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: