![](/img/trans.png)
[英]Reading from multiple XML files and displaying data in a ListBox issue
[英]reading .log files and displaying the data
我有一個日志文件,看起來像:
2019-12-24 18:00:17.8105|DEBUG|--------------------------------
https://...
2019-12-24 18:00:17.8105|DEBUG|Key: xxxxxxxxxxxxxxxxxxxxxxxx
{
"Id": "xxxxxxx",
"Times": "2019-12-24",
"Data": {
"Id": 8,
"Code": "5",
"Description": "abc",
},
"Number": 1,
...
}
2019-12-24 18:00:17.8105|DEBUG|--------------------------------
https://...
2019-12-24 18:00:17.8105|DEBUG|Key: xxxxxxxxxxxxxxxxxxxxxxxx
{
"Id": "xxxxxxx",
"Times": "2019-12-24",
"Data": {
"Id": 6,
"Code": "3",
"Description": "def"
},
"Number": 3,
...
}
//...and it repeats several times in this file with diferent data
我的目標是只獲取 "{ ... }" 中的部分並將其添加到對象數組中,就像
Array:
[
{"Id": "xxxxxxx", "Times": "2019-12-24", "Data": { "Id": 8, "Code": "5", "Description": "abc"}}
{"Id": "xxxxxxx", "Time": "2019-12-24", "Data": { "Id": 6, "Code": "3", "Description": "def"}}
]
到目前為止我所擁有的:
我知道我可以使用File
對象來讀取文件,所以在我的 index.cshtml 中我放了:
@{
var result = "";
Array log = null;
var dataFile = Server.UrlPathEncode("C:/Temp/test.log");
if (File.Exists(dataFile))
{
log = File.ReadAllLines(dataFile);
if (log == null)
{
result = "The file is empty.";
}
}
else
{
result = "The file does not exist.";
}
}
但我不知道如何獲取大括號內的內容並將其轉換為對象
注意事項:
更新:
獲取 .log 文件的一部分,我做了:
foreach (var item in log)
{
text += item;
}
Regex regex = new Regex(@"(?={)[^}]*(?=})", RegexOptions.IgnoreCase);
matches = regex.Matches(text);
但是這個正則表達式並沒有得到我想要的一切,直到"Description": "abc",}
,我也想得到"Number": ...
我使用此鏈接文本正則表達式
有人可以幫助使用正則表達式嗎?
選項 1:使用像 (?<={)[^}{]*(?=}) 這樣的正則表達式從日志文件中獲取 JSON 內容。
Regex regex = new Regex(@"(?<=\{)[^}{]*(?=\})", RegexOptions.IgnoreCase);
MatchCollection matches = regex.Matches(str);
選項 2:循環遍歷所有行,如果找到 {,請繼續將以下行添加到字符串中,直到找到 }。 你必須記下 { 的數量應該與 } 的數量相匹配
以下示例將起作用:
public class MyData
{
public string Id { set; get; }
public string Times { set; get; }
public Data Data { set; get; }
public string Number { set; get; }
}
public class Data
{
public string Id { set; get; }
public string Code { set; get; }
public string Description { set; get; }
}
var lines = File.ReadAllLines(@"C:\Temp\data.txt").Where(line => !line.StartsWith("2019"));
var jsonString = "[" + String.Join("", lines) + "]";
jsonString = jsonString.Replace("}", "},");
jsonString = jsonString.Replace("},,", "},");
var myObjectDT = JsonConvert.DeserializeObject<List<MyData>>(jsonString);
foreach(var item in myObjectDT)
{
string line = JObject.FromObject(item).ToString(Formatting.None);
//write line to file
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.