将文件名与服务器上已有(附加)的数据库进行比较

时间:2017-03-15 09:24:35

标签: c# sql-server

我需要将文件名(.mdf)与SQL服务器上的现有数据库进行比较,但我不知道如何。未附加的数据库必须显示在datagridview中。

以下是目前的代码:

private void loadDB_Click_1(object sender, EventArgs e)
{
    String[] files = Directory.GetFiles(@"C:\Program Files\Microsoft SQL Server\MSSQL10_50.MSSQLSERVER\MSSQL\DATA\", "*.mdf", SearchOption.AllDirectories);

    DataTable table = new DataTable();
    table.Columns.Add("File Name");
    table.Columns.Add("Path");

    for (int i = 0; i < files.Length; i++)
    {
        FileInfo file = new FileInfo(files[i]);
        table.Rows.Add((Path.GetFileNameWithoutExtension(file.Name)),Path.GetFullPath(file.Name));
    }     

    dataGridView2.DataSource = table;
}

1 个答案:

答案 0 :(得分:0)

 DataTable dbTables = new DataTable();
 SqlDataAdapter adap;
 SqlConnection connection = new SqlConnection("yourConnectionString");            
 SqlCommand cmd = new SqlCommand(@"SELECT name FROM master.dbo.sysdatabases ", connection);           

  adap = new SqlDataAdapter(cmd);
  adap.Fill(dbTables);

  string[] dbTableNames = dbTables.AsEnumerable().Select(x => x.Field<string>("name")).ToArray();

  string[] diff = files.Except(dbTableNames).ToArray(); // one of pssibility to check differents

填充DataGridView执行此操作:

dataGridView1.Columns.Add("FileName", "File Name");
for (int i = 0; i < diff.Length; i++)
{
     dataGridView1.Rows.Add(new object[] { diff[i] });
}