设为首页 加入收藏

TOP

C#批量附加指定目录下的所有数据库文件到数据库中(一)
2014-11-24 12:51:48 来源: 作者: 【 】 浏览:2
Tags:批量 附加 指定 目录 所有 数据库 文件

应用场合:因为经常更换操作系统,所以D盘存放数据库文件目录的数据库每次都要一个一个的附加到MSSQL中,因此设计程序批量附加省时间也方便自己和大家。


程序不足:没有去研究跟实现NDF日志文件附加和多个日志文件的数据库附加。


程序源码:



///


/// 循环查找指定目录下要附加的数据库文件和对应的日志文件,连接本地数据库并执行数据库附加命令
///

private void AttachFolderDB()
{
string strFileFolder = "";
FolderBrowserDialog myFolderBrowserDialog = new FolderBrowserDialog();
myFolderBrowserDialog.ShowDialog();
if (myFolderBrowserDialog.SelectedPath != "")
{
strFileFolder = myFolderBrowserDialog.SelectedPath;
}
//查找所有的MDF文件列表
string[] arrAttachFilePath = null;
if (strFileFolder != "")
{
DirectoryInfo dir = new DirectoryInfo(strFileFolder);
//判断目录下是否存在主数据库文件
FileInfo[] finfo = dir.GetFiles("*.mdf");
if (finfo.Length > 0)
{
arrAttachFilePath = new string[finfo.Length];
if (finfo.Length > 0)
{
int i = 0;
foreach (FileInfo f in finfo)
{
arrAttachFilePath[i] = f.FullName;
i = i + 1;
}
}
}


}
//循环附加数据库
if (arrAttachFilePath != null)
{
for (int i = 0; i < arrAttachFilePath.Length; i++)
{
string strFile = arrAttachFilePath[i].ToString();
string strMdfFilePath = arrAttachFilePath[i].ToString();//mdf路径
string strLogFilePath = "";//日志文件路径
string strLdfFilePath = "";//日志文件路径
string strDataFileName = strMdfFilePath.Substring(strMdfFilePath.LastIndexOf("\\") + 1, strMdfFilePath.Length - strMdfFilePath.LastIndexOf("\\") - 1);
strDataFileName = strDataFileName.Remove(strDataFileName.LastIndexOf("."));


string logIndex = "_Data";
int n = strDataFileName.IndexOf(logIndex);


if (n == -1)
{
strLogFilePath = strMdfFilePath.Remove(strMdfFilePath.LastIndexOf("\\")) + "\\" + strDataFileName + "_log.ldf";
strLdfFilePath = strMdfFilePath.Remove(strMdfFilePath.LastIndexOf("\\")) + "\\" + strDataFileName + ".ldf";
}
else
{
strDataFileName = strDataFileName.Remove(strDataFileName.LastIndexOf("_"));
strLogFilePath = strMdfFilePath.Remove(strMdfFilePath.LastIndexOf("\\")) + "\\" + strDataFileName + "_log.ldf";
strLdfFilePath = strMdfFilePath.Remove(strMdfFilePath.LastIndexOf("\\")) + "\\" + strDataFileName + ".ldf";
}


StringBuilder sb = new StringBuilder();
sb.Append("sp_attach_db @dbname='" + strDataFileName + "',@filename1='" + strMdfFilePath + "'");
if (System.IO.File.Exists(strLogFilePath))
{
sb.Append(",@filename2='" + strLogFilePath + "'");
AttachDataBas

首页 上一页 1 2 下一页 尾页 1/2/2
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇Python中__init__.py文件的作用 下一篇MySQL源代码:为MySQL增加响应时间..

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容:

·如何利用Python做数 (2025-12-24 23:48:36)
·如何使用python进行 (2025-12-24 23:48:34)
·python 爬虫入门该怎 (2025-12-24 23:48:31)
·Java 实现多个大文件 (2025-12-24 23:22:00)
·Java多线程编程在工 (2025-12-24 23:21:56)