Skip to main content
 首页 » 编程设计

c#之如何使用打开文件对话框打开 json 文件

2024年02月13日19www_RR

我有这段代码可以将 Person 对象保存为 JSON 文件。

if (saveWork.ShowDialog() == DialogResult.OK) 
        { 
            string output = JsonConvert.SerializeObject(MyPerson); 
            try 
            { 
                string name = saveWork.FileName; 
                using (System.IO.StreamWriter sw = new StreamWriter(name)) 
                    sw.WriteLine(output); 
            } 
 
            catch (Exception ex) 
            { 
                MessageBox.Show(ex.Message); 
            } 
        } 

现在我正在处理打开文件对话框的代码,但我被卡住了,我尝试的任何事情似乎都不起作用。这是我现在的代码,他在“file.json”上给出了一个错误。我知道为什么,但我不知道如何获取它的文件名。

if (openWork.ShowDialog() == DialogResult.OK) 
        { 
            DialogResult result = openWork.ShowDialog(); 
            //Person file = JsonConvert.DeserializeObject(result); 
 
            using (StreamReader r = new StreamReader("file.json")) 
            { 
                string json = r.ReadToEnd(); 
                Person items = JsonConvert.DeserializeObject<Person>(json); 
            } 
        } 

请您参考如下方法:

您应该使用 OpenFileDialog 中的属性 FileName 来检索文件的名称

    openWork.CheckFileExists = true; 
    if (openWork.ShowDialog() == DialogResult.OK) 
    { 
        // Check if you really have a file name  
        if(openWork.FileName.Trim() != string.Empty) 
        { 
            using (StreamReader r = new StreamReader(openWork.FileName)) 
            { 
                string json = r.ReadToEnd(); 
                Person items = JsonConvert.DeserializeObject<Person>(json); 
            } 
        } 
    } 

我还为 true 添加了一个 CheckFileExists 属性,以便在用户指定不存在的文件名时显示警告。