Fastest way to copy files from one directory to another

前端 未结 4 1395
死守一世寂寞
死守一世寂寞 2020-12-10 09:57

I need to copy files from one directory to another, depending on the existence of the file name in a table of SQL database.

For this I use the following code:

<
4条回答
  •  臣服心动
    2020-12-10 10:14

    Since your i/o subsystem is almost certainly the botteneck here, using the parallel task library is probably about as good as it gets:

    static void Main(string[] args)
    {
      DirectoryInfo source      = new DirectoryInfo( args[0] ) ;
      DirectoryInfo destination = new DirectoryInfo( args[1] ) ;
    
      HashSet filesToBeCopied = new HashSet( 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 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() ;
    
      }
    }
    

提交回复
热议问题