对不起标题,老实说,我不知道如何描述那里的问题。无论如何,这是我的困境。我目前正在解析一个信息文件。它的“作者”和“依赖项”部分是相似的。但是,信息文件的创建者可以选择以不同的方式编写他们的文件。它可以写成:
"authors" : [ "author1", "author2" ],
或者:
"authors": ["author1", "author 2"],
我需要把这两种风格都变成:
author1, author2
我试图解析的文件如下所示:
-snip "authors": [ "author1", "author2", "author3" -snip
我已经成功地解析了作者编写它的第二种方式。但是,当我尝试解析第一种方式时,我得到一个 NullReference 异常。异常详情如下:
System.NullReferenceException 未被用户代码处理 HResult=-2147467261 消息=对象引用未设置为对象的实例。Source=RKs Tool Kit StackTrace: at RK_Tool_kit.ParseModInfo.getAuthors(String path) in C:\Users\Sam\Desktop\Programing\C# Projects\RK Mod Installer\RK Mod Installer\RK Mod Installer\ParseModInfo.cs:line 119在 RK_Tool_kit.AddMods.txtbxAddMods_DragDrop(Object sender, DragEventArgs e) 在 C:\Users\Sam\Desktop\Programing\C# Projects\RK Mod Installer\RK Mod Installer\RK Mod Installer\AddMods.cs:line 85 at System.Windows .Forms.Control.OnDragDrop(DragEventArgs drgevent) 在 System.Windows.Forms.Control.System.Windows.Forms.IDropTarget.OnDragDrop(DragEventArgs drgEvent) 在 System.Windows.Forms.DropTarget.System.Windows.Forms。
内部异常:
我在这里不知所措。提前非常感谢。这是我的代码:
public static string getAuthors(string path)
{
string line;
using (StreamReader sr = new StreamReader(path))
{
while (!sr.EndOfStream)
{
line = sr.ReadLine();
if (line.Contains("author"))
{
//This detects if it is the second way the authors can write it
if (line.Contains("[") && line.Contains("]"))
{
line = line.Replace("\"authors\": ", "").Replace("\"authors\" : ", "").Replace("\"authorList\": ", "").Replace("\"authorList\" : ", "").Replace("[", "").Replace("]", "").Replace("\"", "").TrimStart(toTrim);
int Place = line.LastIndexOf(",");
string comma = ",";
line = line.Remove(Place, comma.Length).Insert(Place, "");
return line;
}
//This means the the author wrote it the first way. And the string "line" just says '"authors": [' so we want to read the line again.
else
{
line = sr.ReadLine();
line = line.Replace("\"", "").TrimStart(toTrim);
for (int i = 0; i < 101; i++)
{
//This checks to see if there is only one author in the array. If there is a comma, we want to read another line because there is another author.
if (line.Contains(","))
{
//THIS RIGHT HERE throws the exception
line = line + sr.ReadLine().Replace("\"", "").TrimStart(toTrim);
}
else
{
break;
}
}
return line;
}
}
}
}
return "N/A";
}