数据库中海量文件的批量转移方法
摘要:今天我们将谈到的是在数据库中海量文件的批量转移,如果这样的问题不解决会影响到相关文件的维护工作。
事情的经过是这样子的!数据库A表添加一条记录,**系统中B目录下就会多出5n个文件。随着系统运行3年多,B目录中的文件数已高达2M多,而这些文件恰恰又是用户高度频繁访问的。于是问题就来了,一方面是用户访问文件速度变慢了;另一方面是文件太多,很难维护。
怎么办呢?思许良久,发现A表中有个录入时间字段是不会变更的。如果截取录入时间的年份+月份组成,用来创建B目录下的子目录名,把当年当月新增的文件统一归档于该子目录下,不就可以吗?新增的文件好处理,可对于旧文件归档需要费点周折,因为文件得迁移到新的子目录里。
下面是关于文件迁移的主要代码:
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 49 50 | 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 Class 和 Directory Class 的使用方法。
执行效果图如下:
Tips:
目录名(年份+月份) 如:201101
c# =DateTime.Now.ToString("yyyyMM")
SQL=convert(varchar(6),getdate(),112)
当然仅仅文件迁移是不够的,还有很多工作要做,比如修改程序;更新数据库表记录等等。我知道,这次“手术”不符合开放-关闭原则,但也是无奈之举。欢迎各位园友多多拍砖!