I am copying files from one place to another when a USB Storage device is inserted into the computer, and my code is based off this MSDN example. However, whenever I run it and insert a flash drive (/memory stick/pen drive etc), the code runs, and throws the following exception:
System.IO.IOException: The process cannot access the file 'H:\Test document.txt' because it is being used by another process.
at System.IO.__Error.WinIOError(Int32 errorCore, String maybeFullPath)
at System.IO.File.InternalCopy(String sourceFileName, String destFileName, Boolean overwrite, Boolean checkHost)
at System.IO.File.Copy(String sourceFileName, String destFileName, Boolean overwrite)
at the location in my source.
H:\Test document.txt
is the source file.
This is my source:
private int sync(string source, string target)
{
MessageBox.Show("Running - "+source+"->"+target);
//TODO: Iterate through directory tree
if (!Directory.Exists(source))
{
MessageBox.Show("Failed");
return 1; //Source doesn't exist
}
if (!Directory.Exists(target))
{
MessageBox.Show("Creating target");
Directory.CreateDirectory(target);
}
try
{
string[] files = Directory.GetFiles(source);
foreach (string str in files)
{
string fileName = Path.GetFileName(str);
string fileDestPath = Path.Combine(target, str);
File.Copy(str, fileDestPath, true); //This is the line where the exception is being thrown
}
}
catch (Exception e)
{
MessageBox.Show("exception thrown - " + e); //above exception is being caught here
}
MessageBox.Show("Copied");
return 0;
}
Why is it throwing the exception when trying to read the file (all the issues I've seen on the web have been related to writing files, which makes sense), and is there anything that I can do to stop it.