首页 > 解决方案 > Json 数据的保存方式取决于本地或根文件路径

问题描述

我创建了一个简单的类,它使用 txt 文件写入和读取 json 数据:

 using System;
 using System.IO;
 using Newtonsoft.Json;
 
 namespace JsonTest1
 {
     class Program
     {
         private const string filePath = @"..\jsonData.txt";

         static void Main(string[] args)
         {
             JsonFileTest();
             NewPerson();
             DeSerializer();
             Console.ReadLine();
         }
 
         //Tests if the project's storage file exists.
         public static void JsonFileTest()
         {
             bool exists = File.Exists(filePath);
 
             if (exists)
             {
                 Console.WriteLine("File exists at filepath " + filePath);
             }
             else
             {
                 Console.WriteLine(filePath + " not found.");
             }
         }
 
         //Creates a test object of 'Person' then passes it to the serializer method.
         public static void NewPerson()
         {
             Person person = new Person();
             person.Name = "John Wick";
             person.Age = 999;
             SerializeMethod(person);
         }
 
         //Turns an object into JSON data and writes it to file.
         static void SerializeMethod(Person person)
         {
             File.WriteAllText(filePath, JsonConvert.SerializeObject(person));
             Console.WriteLine("Test name and age copied to file.");
         }
 
         //Turns JSON data from file into an object.
         static void DeSerializer()
         {
             Person person2 = JsonConvert.DeserializeObject<Person>(File.ReadAllText(filePath));
             if (person2 != null)
             {
                 Console.WriteLine("Json-to-C# test data: " + person2.Name + ", " + person2.Age);
             }
             else
             {
                 Console.WriteLine("No data received for json-to-C# test object.");
             }
         }
     }
 }

问题是,如果我将 filePath 设置为类似@"C:\Users\User\Documents\json.txt",那么它将创建一个文本文件,之后我可以看到其中的数据。如果filePath是本地的,例如@"..\jsonData.txt",我打开文件并且它是空的,即使我的程序可以在运行时正确读取它。为什么我使用本地文件路由时没有保存数据?

我已经尝试过的事情:使用.json文件而不是.txt文件。以管理员身份运行 Visual Studio。

标签: c#jsonjson.net

解决方案


您在错误的文件夹中查找。您的程序将从bin\debug文件夹或其他地方执行。..然后是bin文件夹。

解决“找不到文件”问题的一般方法是使用免费程序SysInternals Process Monitor。添加具有属性Path, contains,的过滤器jsonData.txt,单击Add,然后让您的程序运行。

路径包含过滤器

这将显示完整路径:

结果

然后Jump to...在上下文菜单中单击以显示该路径。

跳到


推荐阅读