获取资源文件方法

时间:2022-09-03 18:43:49
获取Message方法:

public class ResourceHelper {
private static ErrorCode ErrorMsg;
private static string ResourcePath = ConfigManager.Configs["ResourceParames"].ResourcePath.Value;
static ResourceHelper()
{
ErrorMsg = GetErrorMessage();
}

private static ErrorCode GetErrorMessage()
{
string path = System.IO.Path.Combine(HttpContext.Current.Server.MapPath("~/"), ResourcePath);
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(path);
using (StringReader sr = new StringReader(xmlDoc.OuterXml))
{
XmlSerializer xmldes = new XmlSerializer(typeof(ErrorCode));
ErrorCode errorInfo = xmldes.Deserialize(sr) as ErrorCode;
return errorInfo;
}
}

public static Message GetMessage(string errorCode)
{
var errorInfo = ErrorMsg.ErrorCodeList.FirstOrDefault(p => p.Key == errorCode);
if (errorInfo == null)
{
return new Message() { Code = "001", Msg = "资源未找到!" };
}
return errorInfo;
}
}

实体类定义:

    
 [XmlRoot("ErrorCode")]
public class ErrorCode
{
[XmlArray("Messages")]
[XmlArrayItem("Message")]
public List<Message> ErrorCodeList { get; set; }
}

public class Message
{
[XmlAttribute("key")]
public string Key { get; set; }

[XmlAttribute("code")]
public string Code { get; set; }

[XmlAttribute("msg")]
public string Msg { get; set; }

}

  

  配置文件格式:

 

    

<?xml version="1.0" encoding="utf-8" ?>
<ErrorCode culture="zh-CHS">
<Messages>
<!--订单-->
<Message key="OrderNotExists" code="OO0001" msg="订单信息不存在" />
<Message key="OrderNotExists" code="OO0001" msg="订单信息不存在" />
<Message key="OrderNotExists" code="OO0001" msg="订单信息不存在" />
<!--门店-->

<!--车辆-->

<!--门店-->
</Messages>
</ErrorCode>

 配置文件路径:ConfigFiles/Ford/ErrorResource.xml