數據庫中海量文件的批量轉移方法

作者: hailibu  來源: 博客園  發布時間: 2011-01-07 10:22  閱讀: 1188 次  推薦: 0   原文鏈接   [收藏]  
摘要:今天我們將談到的是在數據庫中海量文件的批量轉移,如果這樣的問題不解決會影響到相關文件的維護工作。

  事情的經過是這樣子的!數據庫A表添加一條記錄,**系統中B目錄下就會多出5n個文件。隨著系統運行3年多,B目錄中的文件數已高達2M多,而這些文件恰恰又是用戶高度頻繁訪問的。于是問題就來了,一方面是用戶訪問文件速度變慢了;另一方面是文件太多,很難維護。

  怎么辦呢?思許良久,發現A表中有個錄入時間字段是不會變更的。如果截取錄入時間的年份+月份組成,用來創建B目錄下的子目錄名,把當年當月新增的文件統一歸檔于該子目錄下,不就可以嗎?新增的文件好處理,可對于舊文件歸檔需要費點周折,因為文件得遷移到新的子目錄里。

  下面是關于文件遷移的主要代碼:

static void Main(string[] args)
{
    string paperPath = ConfigurationManager.AppSettings["PaperBuildPath"];

    Console.WriteLine(string.Format("試卷目錄:{0}", paperPath));
    Console.WriteLine();
    Console.WriteLine("目錄是否正確? 正確請按任意鍵......");
    Console.WriteLine();
    Console.ReadKey();

    string[] files = Directory.GetFiles(paperPath);

    int num = 0;

    PublicExam[] list = Gateway.Default.FindArray<PublicExam();

    foreach (PublicExam publicExam in list)
    {
        foreach (string file in files)
        {
            //源文件名(去除路徑后)
            string fileName = file.Split('\\').Last();

            if (fileName.StartsWith(publicExam.FGuid.ToString(), StringComparison.CurrentCultureIgnoreCase))
            {
                //目標文件夾
                string destFilePath = paperPath + publicExam.FInputTime.ToString("yyyyMM");

                if (Directory.Exists(destFilePath) == false)
                    Directory.CreateDirectory(destFilePath);

                //目標文件名
                string destFileName = destFilePath + "\\" + fileName;

                if (File.Exists(destFileName))
                    File.Delete(destFileName);

                Console.WriteLine(string.Format("正在遷移文件:{0}", fileName));

                //遷移文件
                File.Move(file, destFileName);
                num++;
            }
        }
    }

    Console.WriteLine();
    Console.WriteLine(string.Format("共遷移{0}個文件,請按任意鍵退出......", num));
    Console.ReadKey();
}

  上面例子參考了MSDN 關于File ClassDirectory Class 的使用方法。

  執行效果圖如下:

  Tips:

  目錄名(年份+月份) 如:201101

  c# =DateTime.Now.ToString("yyyyMM")

  SQL=convert(varchar(6),getdate(),112)

  當然僅僅文件遷移是不夠的,還有很多工作要做,比如修改程序;更新數據庫表記錄等等。我知道,這次“手術”不符合開放-關閉原則,但也是無奈之舉。歡迎各位園友多多拍磚!

0
0
 
 
 

文章列表

arrow
arrow
    全站熱搜
    創作者介紹
    創作者 大師兄 的頭像
    大師兄

    IT工程師數位筆記本

    大師兄 發表在 痞客邦 留言(0) 人氣()