如何提取Steam VDF文件中apps键名?System.Text.JSON适用性咨询
问题
我正在开发一款需要遍历Steam游戏的应用,需读取libraryfolder.vdf文件,遍历其中的apps节点并提取所有键名(如示例中的730、4560等)保存为字符串。
VDF文件内容示例:
"libraryfolders" { "0" { "path" "D:\\Steam" "label" "" "contentid" "-1387328137801257092942" "totalsize" "0" "update_clean_bytes_tally" "42563526469" "time_last_update_corruption" "1663765126" "apps" { "730" "31892201109" "4560" "9665045969" "9200" "22815860246" "11020" "776953234" "34010" "11967809445" "34270" "1583765638" } } }
目前程序已使用System.Text.JSON,因VDF格式未使用冒号或逗号分隔值,请问能否用该库实现上述需求,还是需采用其他方案?
回答
System.Text.JSON无法直接解析VDF格式文件,因为VDF的语法规则(无冒号分隔键值、无逗号分隔条目、使用大括号嵌套结构)和JSON完全不兼容,强行用JSON解析库处理会直接失败。
推荐两种可行方案:
- 使用专门的VDF解析库:.NET生态中有不少成熟的VDF解析库,比如
ValveKeyValue,这类库专门针对Steam的VDF格式设计,能直接读取libraryfolder.vdf并遍历节点提取数据,只需要调用库的API就能轻松获取apps节点下的所有键名。 - 自行编写简易解析逻辑:如果不想引入第三方库,可以针对
libraryfolder.vdf的结构写一个简单的解析器:- 逐行读取文件内容,过滤掉空白行和注释(如果有的话);
- 跟踪当前是否处于
apps节点的大括号内; - 当检测到
"apps"后进入对应的大括号区域,提取每一行中第一个引号包裹的字符串(即游戏ID),直到离开apps的大括号。
比如简易解析的核心逻辑示例(C#):
List<string> gameIds = new List<string>(); bool inAppsSection = false; int braceDepth = 0; foreach (var line in File.ReadLines("libraryfolder.vdf")) { var trimmedLine = line.Trim(); if (trimmedLine.StartsWith("\"apps\"")) { inAppsSection = true; continue; } if (!inAppsSection) continue; if (trimmedLine == "{") { braceDepth++; continue; } if (trimmedLine == "}") { braceDepth--; if (braceDepth == 0) { inAppsSection = false; break; } continue; } if (trimmedLine.StartsWith("\"") && braceDepth == 1) { var idEndIndex = trimmedLine.IndexOf("\"", 1); if (idEndIndex > 0) { var gameId = trimmedLine.Substring(1, idEndIndex - 1); gameIds.Add(gameId); } } }
内容的提问来源于Stack Exchange,提问作者Lachie
相关产品推荐
相关产品推荐

