質問

I have this code to save a Person object as a JSON file.

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);
            }
        }

Now I am working on the open file dialog code but I am stuck, nothing I try seems to work. This is the code I have now, he gives an error on the "file.json". I know why, but I don't know how to get the file name for it.

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);
            }
        }
役に立ちましたか?

解決

You should use the property FileName from the OpenFileDialog to retrieve the name of your file

    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);
            }
        }
    }

Also I have added a CheckFileExists property to true to display a warning if the user specifies a file name that does not exist.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top