My post takes the comments about Terraria into account. I haven't tried this, but here's how I would approach the problem if I wanted the best chance of copying the file while keeping Terraria from crashing.
Problem
My guess is that Terraria is crashing because it needs write access to the file while you are trying to copy it. I also thereby assume that File.Copy
opens the file with no sharing access, so a different mechanism for opening and copying the file is needed to solve the problem.
Solution
You need some way to open and read from the file, while still leaving Terraria the right to simultaneously open and write to the file. I'm not 100% positive that this approach will do that, and it will depend on how Terraria is trying to open the file, but you can at least open the file so that sharing is still allowed. Instead of File.Copy
, try:
using (FileStream inStream = new FileStream(filename, FileMode.Open,
FileAccess.Read, FileShare.ReadWrite) {
// Specifying shared access as FileShare.ReadWrite is the key, as it lets
// Terraria open the file with write access.
// Then add code here to copy the file out to your destination...
// this depends a bit on which version of .Net you are using, but
// inStream.CopyTo(outStream) is probably the easiest as long as you
// are using .Net 4+.
}
Conclusion
If your open fails, or your copy fails (exception), or your FileSystemWatcher signals while you are copying, it means Terraria is using the file and you will need to retry later. In any case, hopefully you will be able to stay out of Terraria's way.
I am very interested to hear if this approach works for you. Please comment if you give it a try.