1

I have a Visual C# 2008 project. Within my project explorer, I have an SQL CE database (sdf file) so I can work with the database and dataset in the designer. At runtime, the sdf file is copied to the output directory. When the user saves their own database, this sdf file is copied to whatever filename the user chooses and their dataset is saved to the copy. No problem so far.

I'd like to do this a different way if possible. Rather than having the sdf file copied out when the program first runs, I'd like to set it up so that when the user saves their database, THEN it copies out the sdf file using the name of their choosing and saves their dataset to it.

I have read ways to write out the file as binary, which does work but it takes several lines of code that just seems unnecessary. Isn't there a way just to tell the program "hey, go ahead and copy this sdf file out real quick"? After all, the program is able to automatically do it when you first run it.

Cœur
  • 37,241
  • 25
  • 195
  • 267
Kyle Vegas
  • 89
  • 5
  • What language do you want this script to be in and what have you tried? – Cole Tobin Sep 01 '12 at 00:55
  • (Visual) C#, as I said. Sorry if I wasn't clear enough. Right now, the file is set to just set to "copy always". I have tried a method that writes the file out in a binary stream, as suggested somewhere on stackoverflow which I can't seem to find now but as I said, it just seems to take too much code and I thought there had to be a simple command to export the file since the program has the ability to do it when you first run it. I know I could save the file out at design time and include it as a resource for easy export, but it seemed redundant to have the file twice in the solution. – Kyle Vegas Sep 01 '12 at 01:11

2 Answers2

1

Add the database file as a resource in your project. Then when you want the file to be appear just write out the byte array to a file.

Example:

File.WriteAllBytes("destination path", Properties.Resources.YourResourceName);
coolmine
  • 4,427
  • 2
  • 33
  • 45
  • I'm aware that I can add it as a resource and simply "write all bytes" and I'm not entirely against the idea. It just seems a bit redundant considering the file is already in the project, in my solution explorer. And since I have the option to choose "copy if newer" or "copy always" (meaning the program CAN export the file from there), that there would be a simple single line of code like you just posted. If I'm wrong however, your method is probably my best bet. – Kyle Vegas Sep 01 '12 at 01:21
  • The method I'm point out means the database will be inside the .exe itself. Where's the options you mention above means you need to ship your .exe with an extra file (the database file). Alternative, it is possible to programatically create a database using certain classes depending on which type of database are you using. Hard to give you more info without knowing which database you are currently using. But keep in mind it will involve recreating the tables/columns/properties of each column and so on programatically. – coolmine Sep 01 '12 at 01:25
  • Just noticed that your question mentions the database you are using. Take a look at http://stackoverflow.com/questions/6196274/create-sqlce-database-programatically & http://stackoverflow.com/questions/1487845/create-sql-server-ce-database-file-programmatically – coolmine Sep 01 '12 at 01:36
  • Edit : Sorry, I see you replied. Ignore this for now. – Kyle Vegas Sep 01 '12 at 02:05
  • I read your links. I don't need to create a database programatically. It's already created in the designer, with a table schema. I simply need to export it whenever I need to, which it seems your "writeallbytes" method will work for. Can I just use the "Embedded Resource" build action, or do I need to physically add the file to my resources seperately (which is what I was trying to avoid) ? – Kyle Vegas Sep 01 '12 at 02:09
  • Both ways are possible, the one I mentioned makes it easier to access the resource since it required less code. But you can just set your existing resource as embedded resource and extract it from there. Use this as a guideline http://support.microsoft.com/kb/319292 – coolmine Sep 01 '12 at 02:19
  • (EDIT: turns out I'm wrong on this, it's just copying the file that's already in the output directory) I think I just discovered what I've been looking for... that "one line of code to just copy the file out". After changing the Build Action to "Embedded Resource", I tested this: 'File.Copy("file.sdf", @"C:\file.sdf");' and the file exported. Strange how obscure this method is, as I kept finding methods that just over complicate such a simple task with all kinds of bytereading and streams and jargon not needed to get the sdf file dumped. – Kyle Vegas Sep 01 '12 at 02:35
  • Yeap, I was curious why something like that should work when reading the link you provided. But as I mentioned above, if you want to avoid streams etc just add the file in your project resources and use the one liner in the answer above. – coolmine Sep 01 '12 at 02:41
  • Now that I've taken a second to let my brain reset from the overload lol... I now have a grasp on this. If I want to use just one simple line of code, I will have to add the file to project resources. If I use the "embedded resource" build action, I will have to use the more involved method with more code, which I also know how to do. It's not the answer I wanted to hear but it's the right answer. You've been very helpful and everything has been clarified. Thank you for your time and patience! – Kyle Vegas Sep 01 '12 at 02:48
  • No worries. You have three methods in the comments, the ones you mentioned plus the method on the 3rd comment. It's just a matter of choosing which one you prefer based on how much time you want to devote on implementing the solution since all three do the same exact thing :) – coolmine Sep 01 '12 at 02:53
0

i love to share my knowledge with you stack users you can analyse this code find something can help

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Linq;

using System.Text;

using System.Windows.Forms;

using System.Data.SqlServerCe;

using System.IO;

namespace localdatabaseconnect

{

public partial class Form1 : Form

{
    public Form1()
    {
        InitializeComponent();
    }
    string conString = Properties.Settings.Default.locallyConnectionString;
    private void button1_Click(object sender, EventArgs e)
    {


        // Open the connection using the connection string.
        using (SqlCeConnection con = new SqlCeConnection(conString))
        {
            con.Open();

            // Insert into the SqlCe table. ExecuteNonQuery is best for inserts.
            int id = int.Parse(textBox1.Text);
            string nom = textBox2.Text;
            string prenom = textBox3.Text;
            using (SqlCeCommand com = new SqlCeCommand("INSERT INTO testme (id,nom,prenom) VALUES(@id,@nom,@prenom)", con))
            {
                com.Parameters.AddWithValue("@id", id);
                com.Parameters.AddWithValue("@nom", nom);
                com.Parameters.AddWithValue("@prenom", prenom);
                com.ExecuteNonQuery();
            }
            con.Close();
        }
    }

    private void button2_Click(object sender, EventArgs e)
    {
        using (SqlCeConnection con = new SqlCeConnection(conString))
        {
            con.Open();
            // Read in all values in the table.
            using (SqlCeCommand com = new SqlCeCommand("SELECT * FROM testme", con))
            {
                SqlCeDataReader reader = com.ExecuteReader();
                while (reader.Read())
                {
                    string num = reader[0].ToString();
                    MessageBox.Show("hi"+num);
                }
            }
            con.Close();
        }
    }

    private void button3_Click(object sender, EventArgs e)
    {

        string path = "c:\\ChekatyResources";
     try{

      if (!Directory.Exists(path))
        {

      // Try to create the directory.
          DirectoryInfo di = Directory.CreateDirectory(path);
         MessageBox.Show("file is created");
         }
       else {

          MessageBox.Show("file is exist");

          }
          }
            catch (IOException ioex)
           {
  MessageBox.Show(ioex.Message);
           }

       }

    private void Form1_Load(object sender, EventArgs e)
    {
        //string executable = System.Reflection.Assembly.GetExecutingAssembly().Location;

        //string path = (System.IO.Path.GetDirectoryName(executable));
        //MessageBox.Show(path);
        //File.WriteAllBytes("destination path",);
        string paths = "c:\\";
        AppDomain.CurrentDomain.SetData("DataDirectory", paths);

        string connStr = @"Data Source =c:\ChekatyResources\locally.sdf;";

        if (!File.Exists(@"c:\ChekatyResources\locally.sdf"))
        {

            SqlCeEngine engine = new SqlCeEngine(connStr);
            engine.CreateDatabase();

            SqlCeConnection conn = null;


            try
            {
                conn = new SqlCeConnection(connStr);
                conn.Open();

                SqlCeCommand cmd = conn.CreateCommand();
                cmd.CommandText = "CREATE TABLE testme(id int, prenom ntext,nom ntext)";
                cmd.ExecuteNonQuery();
            }
            catch
            {

            }
            finally
            {
                conn.Close();
            }
        }
        else { MessageBox.Show("it's exist"); }
    }
}

}

elaz
  • 121
  • 1
  • 5