Search code examples
c#sdf

C# all database connections in a directory


I currently have a directory with many project folders, and each project folder contains a MysqlCE database. These databases all have the same tables; they are identical aside from the data. My goal is to display the data from _Users tables from each of the databases inside a root directory tree.

I have limited experience with C#, but I am confident I can pull this off with a little research. However, I'd appreciate any pointers - since project folders could be added in the future, I would need the application to "scan" for databases at every run (if this is even possible).

Is this sort of dynamic database connection possible with C#? Can I use multiple data sources together in, say, a dataGridView?


Solution

  • A T4 template could gather the full path of the Databases.

    <#@ template debug="true" hostSpecific="true" #>
        <#@ output extension=".cs" #>
        <#@ Assembly Name="System.Core" #>
    
        <#@ import namespace="System" #>
        <#@ import namespace="System.IO" #>
        <#@ import namespace="System.Collections.Generic" #>
    
        <# 
        string path  = @"~\YourProjectPath";
        List<string> dbFiles = GetDBFilesRecursive(path)
        #>
        //Your class code goes here
        <#+
        public List<string> GetDBFilesRecursive(string path)
        {
    
            List<string> files = new List<string>();
    
            try
            {
                string[] fileEntries = Directory.GetFiles(path);
                foreach (string fileName in fileEntries)
                    files.Add(fileName);
                string [] subdirectoryEntries = Directory.GetDirectories(path);
                foreach(string subdirectory in subdirectoryEntries)
                    files.AddRange(GetDBFilesRecursive(subdirectory));
            }
            catch(Exception e)
            {
                throw new Exception("exception occured in tt gen",e );
            }
            return files;
        }
    #>