我需要将文件从一个目录复制到另一个目录,具体取决于SQL数据库表中是否存在文件名.
为此,我使用以下代码:
using(SqlConnection connection = new SqlConnection("datasource or route"))
{
connection.Open();
using(SqlCommand cmd = new SqlCommand("SELECT idPic, namePicFile FROM DocPicFiles", connection))
using (SqlDataReader reader = cmd.ExecuteReader())
{
if (reader != null)
{
while (reader.Read())
{
//picList IS AN ARRAY THAT Contains All the files names in a directory
if (picList.Any(s => s.Contains(reader["namePicFile"].ToString())))
{
File.Copy("theFile in the Directory or array picList", "the destiny directory"+ ".jpg", false)
}
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
有没有什么办法可以在更短的时间内完成?这需要1小时,为20.876记录.
File.Copy和它一样快.您必须记住,您依赖于硬件和20000文件指定的文件传输速度,数据访问的延迟也会发挥作用.如果你在硬盘驱动器上这样做,你可以看到切换到SSD或其他快速介质后的重大改进.
仅就这种情况而言,硬件很可能是您的瓶颈.
编辑:我认为保持与数据库的连接打开这么长时间是一种不好的做法.我建议你在一些内存缓存(数组,列表,等等)中获取所有需要的数据,然后在复制文件时迭代它.数据库连接是一种宝贵的资源,对于必须处理高并发性的应用程序(但不仅仅是),快速释放连接是必须的.
请允许我猜一猜 - 嗯...不。没有办法做得更快。
我怎么这么自信?因为文件复制需要与磁盘交谈,这是一个非常缓慢的操作。更进一步,如果您尝试使用多线程,结果会变慢而不是变快,因为在磁盘上移动磁头的“机械”操作不再是连续的,这可能是偶然发生的。
请参阅我之前提出的这个问题的答案。
所以是的,如果您还没有使用 SSD,请尝试使用它们,否则您已经获得了最好的效果。
下面是一些让我们了解与缓存相比,磁盘写入慢意味着什么的东西。如果缓存访问需要 10 分钟,则意味着从磁盘读取需要 2 年。所有访问如下图所示。很明显,当您的代码执行时,瓶颈将是磁盘写入。最好的办法是让磁盘写入保持顺序。
由于您的 I/O 子系统几乎肯定是这里的瓶颈,因此使用并行任务库可能是最好的:
static void Main(string[] args)
{
DirectoryInfo source = new DirectoryInfo( args[0] ) ;
DirectoryInfo destination = new DirectoryInfo( args[1] ) ;
HashSet<string> filesToBeCopied = new HashSet<string>( ReadFileNamesFromDatabase() , StringComparer.OrdinalIgnoreCase ) ;
// you'll probably have to play with MaxDegreeOfParallellism so as to avoid swamping the i/o system
ParallelOptions options= new ParallelOptions { MaxDegreeOfParallelism = 4 } ;
Parallel.ForEach( filesToBeCopied.SelectMany( fn => source.EnumerateFiles( fn ) ) , options , fi => {
string destinationPath = Path.Combine( destination.FullName , Path.ChangeExtension( fi.Name , ".jpg") ) ;
fi.CopyTo( destinationPath , false ) ;
}) ;
}
public static IEnumerable<string> ReadFileNamesFromDatabase()
{
using ( SqlConnection connection = new SqlConnection( "connection-string" ) )
using ( SqlCommand cmd = connection.CreateCommand() )
{
cmd.CommandType = CommandType.Text ;
cmd.CommandText = @"
select idPic ,
namePicFile
from DocPicFiles
" ;
connection.Open() ;
using ( SqlDataReader reader = cmd.ExecuteReader() )
{
while ( reader.Read() )
{
yield return reader.GetString(1) ;
}
}
connection.Close() ;
}
}
Run Code Online (Sandbox Code Playgroud)