configinfo的数据读取,读取joson格式的数据
public class ConfigInfoRead<T>where T : class,new()
{
private ReaderWriterLockSlim rwl = new ReaderWriterLockSlim();
public string FileName { get; set; }
public string FilePath { get; set; }
public T CurrentConfig { get; set; }
public ConfigInfoRead(string FileName)
{
this.FileName = FileName;
FilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, FileName);
CurrentConfig = Read();
}
public T Read()
{
T val = new T();
if (File.Exists(FilePath))
{
try
{
rwl.EnterReadLock();
string value = File.ReadAllText(FilePath);
if (!string.IsNullOrEmpty(value))
{
try
{
val = (CurrentConfig = JsonConvert.DeserializeObject<T>(value));
return val;
}
catch (Exception)
{
}
}
}
finally
{
rwl.ExitReadLock();
}
}
else
{
Save(val);
}
return val;
}
public void Save(T t)
{
try
{
rwl.EnterWriteLock();
if (!File.Exists(FilePath))
{
try
{
Directory.CreateDirectory(new FileInfo(FilePath).DirectoryName);
CurrentConfig = t;
}
catch (Exception)
{
}
}
File.WriteAllText(FilePath, JsonConvert.SerializeObject(t));
}
catch (Exception)
{
}
finally
{
rwl.ExitWriteLock();
}
}
}
需要读取的信息按照以下方式读取
{“PlcIp”:“192.168.0.100”,“PlcPort”:10000,“TimeOut”:5000}