-
Notifications
You must be signed in to change notification settings - Fork 0
/
ImportDump.cs
48 lines (41 loc) · 1.94 KB
/
ImportDump.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
using System.IO;
using System.Collections.Generic;
using System.Data.SqlClient;
namespace DumpLoader
{
public class ImportDump
{
public ImportDump(ServerOptions options, string path)
{
var logicalName = GetLogicalNameFromDump(options.CONNECTION_STRING, path);
using (SqlConnection connection = new SqlConnection(options.CONNECTION_STRING))
{
string database = Path.GetFileNameWithoutExtension(path);
string sql = @$"IF DB_ID('{database}') IS NOT NULL DROP DATABASE [{database}];
RESTORE DATABASE [{database}] FROM DISK = '{path}'
WITH MOVE '{logicalName.Key}' TO '{Path.Combine(options.LOCATION_DATA, database)}.mdf',
MOVE '{logicalName.Value}' TO '{Path.Combine(options.LOCATION_LOG, database)}.ldf';";
SqlCommand command = new SqlCommand(sql, connection);
command.Connection.Open();
command.ExecuteNonQuery();
}
}
public KeyValuePair<string, string> GetLogicalNameFromDump(string connectionString, string path)
{
var logicalName = new Dictionary<string, string>();
using (SqlConnection connection = new SqlConnection(connectionString))
{
string sql = $"RESTORE FILELISTONLY FROM DISK = '{path}'";
SqlCommand command = new SqlCommand(sql, connection);
command.Connection.Open();
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
logicalName.Add(reader.GetString(reader.GetOrdinal("Type")), reader.GetString(reader.GetOrdinal("LogicalName")));
}
reader.Close();
}
return new KeyValuePair<string, string>(logicalName["D"], logicalName["L"]);
}
}
}