Hi,
I'm trying to create, a fast and somewhat intelligent file copy algorithm (in c# but platform independent).
My goals:
- I don't want to use any platform specific code (no pinvokes or anything)
- I'd like to take advantage of multiple cores but this seems stupid since doing simultaneous reads/writes would seem slower right? (correct me please if I'm wrong)
- I want to keep track of the copying progress so File.Copy is not an option
The code that I've come up with is nothing special and I'm looking into ways of speeding it up:
public bool Copy(string sourcePath, string destinationPath, ref long copiedSize, long totalSize, int fileNum, int fileCount, CopyProgressCallback progressCallback)
{
FileStream source = File.OpenRead(sourcePath);
FileStream dest = File.Open(destinationPath, FileMode.Create);
int size = (int)(1024 * 256); // 256KB
int read = 0;
byte[] buffer = new byte[size];
try
{
while ((read = source.Read(buffer, 0, size)) != 0)
{
dest.Write(buffer, 0, read);
copiedSize += read;
progressCallback(copiedSize, totalSize, fileNum, fileCount, j);
}
return true;
}
catch
{
// No I don't care about exception reporting.
return false;
}
finally
{
source.Close();
dest.Close();
}
}
Things that I've tried and didn't work out:
- Increasing buffer as I go along (loss of speed and caching problems with CD/DVD)
- Tried 'CopyFileEx' - the pinvokes was slowing copying
- Tried many different buffer sizes and 256KB seems the best solution
- Tried to read as I write - slow down
- Changed 'progressCallback' to update UI after 1 second (using Stopwatch class) - this has significantly improved speed
ANY suggestions are welcome - I'll be updating the code/stuff as I try out new stuff. Suggestions don' t have to be code - just ideas.