简体   繁体   中英

Copy executing files from a UNC path

I am writing an application that needs to copy files from a network directory, where the files are currently executing.

I have tried opening the file with

using (var source = new FileStream(fileData.FileName, 
                                   FileMode.Open, 
                                   FileAccess.Read, 
                                   FileShare.ReadWrite))

After I open the file stream I create another stream to copy into.

However, this throws an exception saying that the file is in use by another process. I am not sure how to get around this problem. If I just use file explorer it will copy the files fine. So I know that it is possible, just not sure on how.

EDIT: I have also tried the simple File.Copy(source, destination) and I get the same exception saying the file is in use by another process.

To copy a file that is being used by another process, we have to make use of two services in Windows, and you'll need to verify that these services are not disabled:

  • Volume Shadow Copy
  • Microsoft Software Shadow Copy Provider

They can be left as Manual startup, so they don't need to be running all the time.

For this, we can use any 3rd party tool. Hobocopy is one of them. It will start the two services automatically when needed, and the Volume Shadow Copy service will be turned back off after it's done.

Download Link: https://github.com/candera/hobocopy/downloads

Unzip the file and place them into Lib directory of your project. Then call the process using System.Diagnostics.Process . In your case, just use the following switch as argument: /y (Don't prompt, just copy everything)

Command-Line Syntax:

hobocopy [/statefile=FILE] [/verbosity=LEVEL] [ /full | /incremental ]
     [ /clear ] [ /skipdenied ] [ /y ] [ /simulate ] [/recursive]
     src dest [file [file [ ... ] ]

C# code:

Process process = new Process();
process.StartInfo.UseShellExecute = false;
process.StartInfo.CreateNoWindow = true;
process.StartInfo.FileName = @"Lib\hobocopy.exe";
process.StartInfo.Arguments = @" /y <network-directory> <local-directory> <filename>";
process.Start();

This'll copy any files (hobocopy focuses mainly on copying directories efficiently) that is being used or unused to your destination.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM