1

これを実現するためにサンプルプログラムを作成したので、実際に使用方法を学び、実際のプロジェクトに適用できます。簡単に言うと、私の最初の試行は Person インスタンスをファイルに書き込むことでしたが、後で書き込まれたさまざまなインスタンスを含むリストを作成できませんでした (最初に書き込まれたものしか見ることができず、リストには 1 つの要素しかありませんでした)。そのため、Person インスタンスを辞書に保存し、辞書をファイルに書き込み、新しい要素 (Person インスタンス) を追加する前にファイルから完全な辞書を読み取ることを思いつきましたが、これも達成できませんでした。

私はクラスを持っているとしましょうPerson

[Serializable]
public class  Person
{
    public string name, lname;
    public int age;

    public void newperson(string name,
              string lname,
              int age)
    {
        this.name = name;
        this.lname = lname;
        this.age = age;
    }
}

私のメインクラスには、バイナリ形式を介してファイルを読み書きするための2つのメソッドがあります(正直にここから盗みました、@Daniel Schroeder @deadlydogに感謝します)。

    Person nper = new Person(); //nper, an instance of Person
    Dictionary<string, Person> dict = new Dictionary<string, Person>();
    const string file = @"..\..\data.bin";

_

public static void WriteToBinaryFile<T>(string filePath, T objectToWrite, bool append = false)
    {
        using (Stream stream = File.Open(filePath, append ? FileMode.Append : FileMode.Create))
        {
            var binaryFormatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
            binaryFormatter.Serialize(stream, objectToWrite);
        }
    }

_

public static T ReadFromBinaryFile<T>(string filePath)
{
    using (Stream stream = File.Open(filePath, FileMode.Open))
    {
        var binaryFormatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
        return (T)binaryFormatter.Deserialize(stream);
    }
}

私はこの方法をある程度理解していますが、それらをコーディング/変更することはできず、私の知識を超えています。

書き込み/読み取りをテストするために、いくつかのテキストボックスとbutton1

 private void button1_Click(object sender, EventArgs e)
    {
        //saving textboxes to Person instance 
        nper.newperson(textBox4.Text, textBox5.Text, Convert.ToInt16(textBox6.Text));

        //saving that object into a dictionary<string,Person> the key is the name, the object is the Person itself
        dict[nper.name] = nper;

        //Writting this dict
        WriteToBinaryFile(file, dict, true);
    }

次に、いくつかの分離されたテキストボックスをドラッグして、読みを確認しました。

private void button2_Click(object sender, EventArgs e)
    {
        try
        {
            //read the file and save all into dict (is this working like I think it should? is dict, getting all the data from file?)
            dict = ReadFromBinaryFile<Dictionary<string,Person>>(file);


            //write into diferent textboxes the Person properties, for the key that matches with another text box that i fill manually to check
            textBox1.Text = dict[tbSearch.Text].name;
            textBox2.Text = dict[tbSearch.Text].lname;
            textBox3.Text = dict[tbSearch.Text].age.ToString();
        }
        catch (Exception ex) { MessageBox.Show(ex.ToString()); }

ファイルからすべてのデータを取得しています?button2_Click dict

編集: 試して結果: 最初のボックスにジョン、ドウ、40 クリックを入力してbutton1 から、別のボックス、クラーク、ケント、50 をロードするとします。

「ジョン」とtbSearch入力すると、ジョンの完全なデータが表示されます (名前、姓、年齢) 「クラーク」と入力すると、「指定されたキーが辞書に存在しませんでした」という辞書エラーが表示されます

4

1 に答える 1

1

で append パラメータを false に設定しますWriteToBinaryFile(file, dict, false)

WriteToBinaryFile メソッドの最初の呼び出しが実行されたとき、BinaryFormatter は 1 つの要素で辞書を書き込みます. 2 番目に 2 つの要素で辞書を書きますが、最初の書き込みに追加されます. したがって、BinaryFormatter ストリームをデシリアライズしようとすると、最初のセクションを読み取り、最初の試行で 1 つのキーで辞書を保存します (最初のボタン1クリック)。

于 2015-07-07T00:52:02.143 に答える