c# - 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。
解决方案
您在错误的文件夹中查找。您的程序将从bin\debug
文件夹或其他地方执行。..
然后是bin
文件夹。
解决“找不到文件”问题的一般方法是使用免费程序SysInternals Process Monitor。添加具有属性Path
, contains
,的过滤器jsonData.txt
,单击Add,然后让您的程序运行。
这将显示完整路径:
然后Jump to...
在上下文菜单中单击以显示该路径。
推荐阅读
- javascript - 使用 JavaScipt 上传 Selenium 隐藏文件
- python - 检查变量是否存在
- javascript - 将数组值设置为对象键
- elasticsearch - ES 查询异常
- matlab - 为什么我的代码不能在 Octave 中工作,但在 Matlab 中工作?
- javascript - 具有不同响应的命令上的 discord.js-commando 参数
- c# - MVC5 区域导致构建时间极慢
- javascript - 创建一个由唯一数字组成的数组
- html - 如何根据百里香叶中的双值在单个标签中呈现不同的结果
- rust - 借用引用字符串的结构 - 部分移动后在此处借用的值