3

I currently have a winForms program and I'm fairly new to programming. Right now I have an Item class

public class Item
{
    public string @Url { get; set; }
    public string Name { get; set; }
    public double Price { get; set; }
    public int Index { get; set; }

    public Item(string @url, string name, double price)
    {
        this.Url = url;
        this.Name = name;
        this.Price = price;
    }

    public override string ToString()
    {
        return this.Name;
    }
}

and throughout the program its stored in a dictionary

Dictionary<int, Item>

How can i create a new file type (.buf) and make it save the dictionary so it can be opened?

MikaAK
  • 2,334
  • 6
  • 26
  • 53
  • What is a `.buf` file? Is there a standard format that you need to write to, or are you creating the format? In general it's preferred to save to a database, of course. – David Sep 09 '13 at 00:18
  • 1
    Try marking the class as [Serializable] and writing it to a file as in this answer - http://stackoverflow.com/a/5937722/808532 – Ryan Weir Sep 09 '13 at 00:19
  • So this is a type of thing databases would be used for. I still haven't quite figured out databases or how to use them, i'm still unclear on what they are actually. – MikaAK Sep 09 '13 at 00:21
  • @user2434321 Databases are used to, well, save data. And preferrably do so efficiently, and let you retrieve the data conveniently as well. – millimoose Sep 09 '13 at 00:22
  • From what i can tell it is something i will have to learn inevitably how would you recommend i get started? Also I'm assuming databases save data as a physical file as I've heard of them before the cloud era started – MikaAK Sep 09 '13 at 00:24
  • You can serialize a dictionary to disk using this: http://stackoverflow.com/questions/1299071/serializing-net-dictionary – dcaswell Sep 09 '13 at 00:47
  • I have updated my answer with an example. – acarlon Sep 09 '13 at 01:20

2 Answers2

2

If you want to serialize the dictionary to a file, I suggest you refer here, here and here.

Update

Be sure to look at all the links as there is more than one way to do this, but this is one way - by following this information and adding a public constructor of

public Item() { }

I could then do the following using XamlServices (you will need to add a reference to System.Xaml in your project):

class Program
{
    static void Main()
    {
        Item newItem = new Item( "http://foo", "test1", 1.0 );

        var values = new Dictionary<int,Item>();
        values.Add(1,newItem);                        
        using( StreamWriter writer = File.CreateText( "serialized.buf" ) )
        {                
            XamlServices.Save( writer, values );    
        }

        using( StreamReader tr = new StreamReader( "serialized.buf" ) )
        {
            Dictionary<int, Item> result = (Dictionary<int, Item>)XamlServices.Load( tr );
            //do something with dictionary here
            Item retrievedItem = result[1];                
        }                                                         
    }
}

For information on databases, refer here and here. If you want to get started using a database and WinForms I suggest this.

For deciding between a flat file and a database, refer to the answers here and here. Sorry about all the links, but the info is out there (I know it is hard to find the right search terms when you are starting out). In my own experience, whether or not you use a database depends on: -

  • the complexity of the operations (queries,create,remove,updates,deletes) you want to do.
  • the structure of the data you want to store.
  • where the application will run. For example, if it will be an embedded application on a router (I take it your winforms app will not) then a file might be your only option.
  • similar to the previous point, how lightweight and self-contained you want your application to be.
  • the volume of data to be stored.
Community
  • 1
  • 1
acarlon
  • 16,764
  • 7
  • 75
  • 94
-1
using (var file = File.OpenWrite("myfile.buf"))
foreach (var item in dictionary)
file.WriteLine("[{0} {1}]", item.Key, item.Value); 
pb2q
  • 58,613
  • 19
  • 146
  • 147
Basem Sayej
  • 3,374
  • 1
  • 14
  • 12
  • What about the Dictionary keys, and all the data in the `Item`, all this will do (if you fix the compile errors) is save the Name property to a file. – sa_ddam213 Sep 09 '13 at 00:42
  • Why are you even copying `dict`’s values to a separate array? Just iterate over them in your loop to begin with… – Ry- Sep 09 '13 at 00:51
  • sorry i didnt test my code, the below would work, Dictionary dict = new Dictionary(); dict.Add("element1key","element1value"); dict.Add("element2key","element2value"); dict.Add("element3key","element3value"); string[] arry= new string[dict.Count]; dict.Values.CopyTo(arry, 0); System.IO.File.WriteAllLines(@"C:\myfile.buf", arry); – Basem Sayej Sep 09 '13 at 00:53
  • such a bad answer, please never use this kind of code to acomplish what has been asked – Mauricio Gracia Gutierrez Sep 09 '13 at 01:02
  • I still don’t understand why you’re copying the array. Even without taking into account keys, `System.IO.File.WriteLines(filePath, dict.Values);` should work fine, right? – Ry- Sep 09 '13 at 01:04
  • 2
    and what about values with newlines in them? – Robert Byrne Sep 09 '13 at 01:07
  • i edited my reply, retaining keys and values in the file. Robert , you mean textual values that have lf/cr in them? – Basem Sayej Sep 09 '13 at 01:10
  • guys come on, i edited my reply, why it has been downvoted? its tested and working – Basem Sayej Sep 09 '13 at 01:15
  • Okay, you’re iterating the right way now, but it’s still kind of fragile as a serialization method. (I removed my downvote, by the way) – Ry- Sep 09 '13 at 01:21