我正在尝试使用 C# 和 JSON.NET 将数据写入 json 文件,参考此处建议的已接受答案(How to write a JSON file in C#?)。当我运行下面的代码时,我没有收到任何错误消息,而且数据也没有写入 json 文件。
从功能上讲,我想要实现的是创建一个 json 文件,该文件存储执行 Nunit 测试时完成的操作的时间
我已尝试实施此处建议的解决方案(Deserializing JSON data to C# using JSON.NET)但它没有解决我的问题
public static class ActionTimeHelper
{
private static readonly string _actionTimeLogFileName = "ActionTimeLog_" + string.Format("{0:yyyy_MM_dd_hhmmss}", DateTime.Now);
[ThreadStatic] private static FileStream _fileStream = null;
[ThreadStatic] private static StreamWriter _actionStreamWriter = null;
[ThreadStatic] private static JsonWriter _jsonWriter = null;
[ThreadStatic] private static List<ActionTimeInfo> actionList = new List<ActionTimeInfo>();
public static void CreateActionTimeLogFile(string logPath, string testName)
{
string dir = logPath + testName + @"\";
if (!Directory.Exists(dir))
{
Directory.CreateDirectory(dir);
}
_fileStream = File.Open(dir + _actionTimeLogFileName + ".json", FileMode.CreateNew);
_actionStreamWriter = new StreamWriter(_fileStream);
_jsonWriter = new JsonTextWriter(_actionStreamWriter);
_jsonWriter.Formatting = Formatting.Indented;
JsonSerializer serializer = new JsonSerializer();
serializer.Serialize(_jsonWriter, actionList.ToArray().ToString());
//var jarray = JsonConvert.DeserializeObject<List<ActionTimeInfo>>(actionList.ToArray().ToString());
}
public static void StartActionTime(string actionName)
{
actionList.Add(new ActionTimeInfo()
{
ActionName = actionName,
StartTime = DateTime.Now
});
}
public static void EndActionTime(string actionName)
{
ActionTimeInfo endAction = actionList.Find(actionInfo => actionInfo.ActionName.Equals(actionName));
endAction.EndTime = DateTime.Now;
endAction.ExecutionTime = endAction.EndTime.Subtract(endAction.StartTime);
}
}
public class ActionTimeInfo
{
public string ActionName { get; set; }
public DateTime StartTime { get; set; }
public DateTime EndTime { get; set; }
public TimeSpan ExecutionTime { get; set; }
}
浮云间
相关分类