Exporting data into a file

I need to export some data into a file and import back again

Page 1 of 1

1 Replies - 1119 Views - Last Post: 22 November 2009 - 06:51 AM Rate Topic: -----

#1 Premier2k  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 3
  • View blog
  • Posts: 180
  • Joined: 26-August 08

Exporting data into a file

Posted 22 November 2009 - 05:49 AM

Hi all,

I have my WPF application where users can enter information and this information gets stored in ArrayLists. At some point the user might need to exit out of the application but store whatever he/she has written so far.

Currently I am writing this information to a text, but I'm having problems importing the data back again.

This is my export code:
public void ExportAll()
		{
			System.Windows.MessageBox.Show("Please select a filename for your export", "Confirm", MessageBoxButton.OK, MessageBoxImage.Question);
				// Configure save file dialog box
				Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();
				dlg.InitialDirectory = @"c:\XML Generator\Exports"; // The initial directory when the dialog box is displayed
				if (GlobalClass.fName != "")
				{
					dlg.FileName = GlobalClass.fName; // Default file name is set to the same name as the map
				}
				dlg.DefaultExt = ".exp"; // Default file extension to apply
				//dlg.Filter = "Text documents (.txt)|*.txt"; // Filter files by extension

				// Show save file dialog box
				Nullable<bool> result = dlg.ShowDialog();

				// Process save file dialog box results
				if (result == true)
				{
					// Save document
					string filename = dlg.FileName;
					GlobalClass.expFilename = filename;
					System.Windows.MessageBox.Show("Now I'm going to generate the export and save into the file. Please DO NOT attempt to open the file whilst this is being done.", "Caution!", MessageBoxButton.OK, MessageBoxImage.Warning);
					// Assign the streamwriter to openfile
					openfile = File.CreateText(globalclass.GlobalClass.expFilename);

					// Write in the initial properties of the map
					openfile.WriteLine(GlobalClass.fName);
					openfile.WriteLine(GlobalClass.radSelect);
					openfile.WriteLine(GlobalClass.sh.ToString());
					openfile.WriteLine(GlobalClass.sw.ToString());
					openfile.WriteLine(GlobalClass.lh.ToString());
					openfile.WriteLine(GlobalClass.lw.ToString());
					openfile.WriteLine(GlobalClass.Minreinforce.ToString());

					// Mark where territories begins
					openfile.WriteLine("territories");

					foreach (Territories o in gbl_lisjt.lijst)
					{
						openfile.WriteLine(o.Tname + "," + o.Sx.ToString() + "," + o.Sy.ToString() + "," + o.Lx.ToString() + "," + o.Ly.ToString() + "," + o.CbS + "," + o.CbK + "," + o.CbN + "," + o.CbB + "," + o.NeutVal.ToString());
					}

					// Indicates where territories end and continent assignment begins
					openfile.WriteLine("*endterritories*");
					openfile.WriteLine("continents");

					foreach (Continents c in gbl_clijst.clijst)
					{
						openfile.WriteLine(c.Cname + "," + c.CbO.ToString() + "," + c.CbP.ToString());
						string[] TList = c.ToString().Split(new string[]{", "}, StringSplitOptions.RemoveEmptyEntries); 
						foreach (string option in TList)
						{
							openfile.WriteLine(option);
						}
					}

					openfile.WriteLine("*endcontinents*");

					// If an objective is set then we need to flag this here so the importer picks it up
					if (GlobalClass.Objective == true)
					{
						openfile.WriteLine("objective");
						openfile.WriteLine(GlobalClass.oName);
						foreach (object o in gbl_olist.olist)
						{
							string s = o.ToString();
							openfile.WriteLine(s);
						}   
					}

					openfile.WriteLine("*endobjectives*");

					try
					{
						openfile.WriteLine("borders");
						foreach (Territories border in gbl_lisjt.lijst)
						{
							string[] TList = border.Border.ToString().Split(new string[] { ", " }, StringSplitOptions.RemoveEmptyEntries);
							foreach (string option in TList)
							{
								openfile.WriteLine(option);
							}
						}
						openfile.WriteLine("*endborders*");
					}
					catch (Exception err)
					{
						logit.WriteToLog(Resources.logpath, err.ToString());
					}

					try
					{
						openfile.WriteLine("bombards");
						foreach (Territories bom in gbl_lisjt.lijst)
						{
							string[] TList = bom.Bombard.ToString().Split(new string[] { ", " }, StringSplitOptions.RemoveEmptyEntries);
							foreach (string option in TList)
							{
								openfile.WriteLine(option);
							}
						}
						openfile.WriteLine("*endbombards*");
					}
					catch (Exception err)
					{
						logit.WriteToLog(Resources.logpath, err.ToString());
					}

					openfile.WriteLine("***ENDFILE***");
					openfile.Close();
					return;
				}
		}



I'm not sure how to go about reading line by line, this is a snippet of my import code so far:

public void ImportAll()
		{
			// Configure open file dialog box
			Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
			dlg.InitialDirectory = @"c:\XML Generator\Exports"; // Default directory
			dlg.DefaultExt = ".exp"; // Default file extension

			// Show open file dialog box
			Nullable<bool> result = dlg.ShowDialog();

			// Process open file dialog box results
			if (result == true)
			{
				// Open document
				string filename = dlg.FileName;

				using (StreamReader reader = new StreamReader(filename))
				{
					GlobalClass.fName = filename;
					while (reader.Peek() != -1)
					{
						// Import territories
						string line = reader.ReadLine();;

						string[] parts = line.Split(new char[] { ',' });

						string s1 = parts[0];
						int sx = int.Parse(parts[1]);
						int sy = int.Parse(parts[2]);
						int lx = int.Parse(parts[3]);
						int ly = int.Parse(parts[4]);
						int nv = int.Parse(parts[9]);
						string s_cbs = parts[5].ToString();
						string s_cbk = parts[6].ToString();
						string s_cbn = parts[7].ToString();
						string s_cbb = parts[8].ToString();

						bool cbs;
						bool cbk;
						bool cbn;
						bool cbb;

						if (s_cbs == "True")
							cbs = true;
						else
							cbs = false;
						if (s_cbk == "True")
							cbk = true;
						else
							cbk = false;
						if (s_cbn == "True")
							cbn = true;
						else
							cbn = false;
						if (s_cbb == "True")
							cbb = true;
						else
							cbb = false;

						gbl_lisjt.lijst.Add(new Territories(s1, sx, sy, lx, ly, cbs, cbk, cbn, cbb, nv));
						GlobalClass.TdoneBefore = 1;
						//lbnames.Items.Add(s1);
						GlobalClass.importStarted = false;
					}
				}
			}
		}


Now this needs changing a lot, when the export runs it creates a file, an example of an export is below:
Blah
png
410
410
510
510
0
territories
a,0,0,0,0,False,False,False,False,0
b,0,0,0,0,False,False,False,False,0
c,0,0,0,0,False,False,False,False,0
d,0,0,0,0,False,False,False,False,0
e,0,0,0,0,False,False,False,False,0
f,0,0,0,0,False,False,False,False,0
g,0,0,0,0,False,False,False,False,0
h,0,0,0,0,False,False,False,False,0
i,0,0,0,0,False,False,False,False,0
*endterritories*
continents
*endcontinents*
*endobjectives*
borders
bombards
***ENDFILE***


The first 8 lines I always know what type is going to be written and imported;

The first line is the filename
The second line is a file type being stored
The next 5 lines are ints...

After that it gets a bit more complicated as I'm pulling the data from the ArrayLists, the first set of data being 'territories'

What I want to be able to do is, when the import hits the string 'territories' it knows what is coming, until it hits the string *endterritories*, now I'm not sure how to go about doing this. Perhaps it's just my limited knowledge of StreamReader, or is there a much easier way of doing this?

I hope I've explained myself ok!! :)

This post has been edited by Premier2k: 22 November 2009 - 05:49 AM


Is This A Good Question/Topic? 0
  • +

Replies To: Exporting data into a file

#2 JackOfAllTrades  Icon User is offline

  • Saucy!
  • member icon

Reputation: 6111
  • View blog
  • Posts: 23,671
  • Joined: 23-August 08

Re: Exporting data into a file

Posted 22 November 2009 - 06:51 AM

If you're using > 1.1 (and you appear to be, based on the use of a Nullable book, you should be using generic collections instead of ArrayLists.

Something like this, maybe? I mean it seems pretty basic logic.
private List<Territory> GetTerritories(StreamReader sr)
{
    List<Territory> terrs = new List<Territory>();
    string line;
    // While we haven't reached the end of the file and we haven't
    // found the *endterritories* line
    while (((line = sr.ReadLine()) != null) && 
        String.Compare(line, "*endterritories*, true) != 0)
    {
        // Parse territory from line and add to list.     
    }  
    return terrs;
}

using (StreamReader sr ...)
{
    read preamble
    List<Territory> terrs = LoadTerritories(sr);
}

Was This Post Helpful? 0
  • +
  • -

Page 1 of 1