C# 从模板文件加载文本
目前我在C# 从模板文件加载文本,c#,arrays,file,text,C#,Arrays,File,Text,目前我在数组中有很多字符串,可以填充各种数据。例如: var obj = new Example(); var test = new Test(); // This must be stored in a text file var text = new[] { $"{obj} contains {obj.attribute}", $"This is a {test.title}" } foreach (var line in text) Console.Wr
数组中有很多字符串
,可以填充各种数据。例如:
var obj = new Example();
var test = new Test();
// This must be stored in a text file
var text = new[] {
$"{obj} contains {obj.attribute}",
$"This is a {test.title}"
}
foreach (var line in text)
Console.WriteLine(line);
如您所见,这个文本
数组填充了不同的字符串,其中包含外部数据(例如,来自obj
和测试
对象的数据)
我的问题:
目标是从.txt文件
中读取文本
行,并将它们加载到文本
变量中,因此结果与上面相同
唯一的条件是此文本文件必须包含所有“变量”,如obj
和test.title
,以便打印这些对象中包含的正确数据。如何将这些行存储在.txt文件中并加载到应用程序中?您将需要创建占位符
在文件中,将有以下行:
${obj} contains ${obj.attribute}
This is a ${test.title}"
占位符是${…}
然后需要逐行解析文件
您可以解析占位符
在占位符中,字符串的第一部分是对象的名称
因此,您需要将程序中现有对象的映射器映射到文件中的对象
然后,使用该映射器创建容器
然后将对象从文件映射到容器中的对象,并使用反射获得占位符中定义的值
另一种方式:
您只有占位符和映射器
存档:
${obj} contains ${obj.attribute}
This is a ${test.title}"
映射器(例如字典)
var fileMapper=新字典
{
[“obj”]=“SFS”,
[“对象属性”]=“SFS”
};
现在您需要获取占位符并替换为对象形式字典
反省不是必要的
完整的工作示例(编译和测试)
类示例
{
public void GetFile()
{
var fileMapper=新字典
{
[“obj”]=“SFS”,
[“对象属性”]=“SFS”
};
var fileLines=新列表();
使用(var sr=newstreamreader(“文件名”))
{
var line=string.Empty;
而((line=sr.ReadLine())!=null)
{
ListListofPlaceholders=this.GetPlaceHolders(第行);
对于(变量i=0;i
您需要创建占位符
在文件中,将有以下行:
${obj} contains ${obj.attribute}
This is a ${test.title}"
占位符是${…}
然后需要逐行解析文件
您可以解析占位符
在占位符中,字符串的第一部分是对象的名称
因此,您需要将程序中现有对象的映射器映射到文件中的对象
然后,使用该映射器创建容器
然后将对象从文件映射到容器中的对象,并使用反射获得占位符中定义的值
另一种方式:
您只有占位符和映射器
存档:
${obj} contains ${obj.attribute}
This is a ${test.title}"
映射器(例如字典)
var fileMapper=新字典
{
[“obj”]=“SFS”,
[“对象属性”]=“SFS”
};
现在您需要获取占位符并替换为对象形式字典
反省不是必要的
完整的工作示例(编译和测试)
类示例
{
public void GetFile()
{
var fileMapper=新字典
{
[“obj”]=“SFS”,
[“对象属性”]=“SFS”
};
var fileLines=新列表();
使用(var sr=newstreamreader(“文件名”))
{
var line=string.Empty;
而((line=sr.ReadLine())!=null)
{
ListListofPlaceholders=this.GetPlaceHolders(第行);
对于(变量i=0;iusing System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
namespace ConsoleApplication1 {
public class TemplateParser {
private string content;
public TemplateParser(string fileName) {
Tags = new Dictionary<string, object>();
//TODO: Add exception control. Perhaps move the reading operation outside the constructor
content = File.ReadAllText(fileName);
}
public Dictionary<string, object> Tags { get; private set; }
public void Parse() {
foreach (string key in Tags.Keys) {
if (Tags[key] != null) {
object propertyValue;
int position = key.IndexOf('.');
if (position >= 0) {
string propertyName = key.Substring(position + 1);
propertyValue = GetPropertyValue(Tags[key], propertyName);
} else {
propertyValue = Tags[key];
}
content = content.Replace(string.Concat("{", key, "}"), propertyValue.ToString());
} else {
//TODO: what to do without not specified replacement?
}
}
}
public string[] ToArray() {
return content.Split(new string[] {Environment.NewLine}, StringSplitOptions.RemoveEmptyEntries);
}
private object GetPropertyValue(object obj, string propertyName) {
PropertyInfo pi = obj.GetType().GetProperties().FirstOrDefault(x => x.Name == propertyName);
if (pi != null) {
return pi.GetValue(obj, null);
}
return null;
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1 {
class Program {
static void Main(string[] args) {
TemplateParser parser = new TemplateParser("C:\\myTextFile.txt");
parser.Tags.Add("obj", 1);
parser.Tags.Add("Test", new Test { Id = 1, Title = "This is a text" });
parser.Parse();
foreach (string line in parser.ToArray()) {
Console.WriteLine(line);
}
}
}
class Test {
public int Id { get; set; }
public string Title { get; set; }
}
}
public class TemplateParser
{
private string _content;
public Dictionary<string, object> Variables { get; } = new Dictionary<string, object>();
public TemplateParser(string filepath)
{
try
{
_content = File.ReadAllText(filepath);
}
catch (IOException)
{
Console.WriteLine("File could not be found on the following location:\n" + filepath);
}
}
public void Parse()
{
var placeholder = "";
var beginIndex = 0;
var busy = false;
for (var i = 0; i < _content.Length; i++)
switch (_content[i])
{
case '{':
placeholder = "";
busy = true;
beginIndex = i;
break;
case '}':
if (placeholder != "")
{
var position = placeholder.IndexOf('.');
var success = false;
try
{
object pValue;
if (position >= 0)
{
var pName = placeholder.Substring(position + 1);
pValue = GetPropertyValue(Variables[placeholder.Substring(0, position)], pName);
}
else pValue = Variables[placeholder];
if (pValue == null)
{
Console.WriteLine("Property not found");
throw new KeyNotFoundException("Property not found");
}
_content = _content.Replace("{" + placeholder + "}", pValue.ToString());
success = true;
}
catch (KeyNotFoundException)
{
Console.WriteLine("WARNING: Placeholder {" + placeholder + "} is unknown");
_content = _content.Replace("{" + placeholder + "}", "x");
}
busy = false;
if (success) i = beginIndex;
}
break;
default:
if (busy) placeholder += _content[i];
break;
}
}
private static object GetPropertyValue(object obj, string propertyName)
{
var pi = obj.GetType().GetProperties().FirstOrDefault(x => x.Name == propertyName);
FieldInfo fi = null;
if (pi == null)
foreach (var x in obj.GetType().GetFields().Where(x => x.Name == propertyName))
{
fi = x;
break;
}
return pi != null ? pi.GetValue(obj) : fi?.GetValue(obj);
}
public string[] ToArray() => _content.Split(new[] {Environment.NewLine}, StringSplitOptions.RemoveEmptyEntries);
}