Level Extreme platform
Subscription
Corporate profile
Products & Services
Support
Legal
Français
File.Copy and lock file
Message
From
19/02/2014 11:55:26
 
 
To
19/02/2014 10:00:21
General information
Forum:
ASP.NET
Category:
Other
Environment versions
Environment:
VB 9.0
OS:
Windows 7
Network:
Windows 2003 Server
Database:
MS SQL Server
Application:
Web
Miscellaneous
Thread ID:
01594636
Message ID:
01594675
Views:
61
>>File.Copy uses the api CopyFile http://msdn.microsoft.com/en-us/library/windows/desktop/aa363851(v=vs.85).aspx
>>
>>Looks like a permission issue
>
>I do not think so. The file copy starts but this is fired as an error in the middle of the copy:
>
>"The process cannot access the file 'MyFile' because it is being used by another process."
>
>So, this is why I am wondering how another action can get a hold of a file while it is being created.
>
>It looks like the other action starts to copy the file while the copy is in progress thus interfering with the initial copy.
>
>Is that possible?


For the copy to succeed neither source nor destination can be in use

You have to test both
		internal static void Go()
		{
			string source, destination;
			source = @"D:\tmp\1.txt";
			destination = @"D:\tmp\2.txt";

			//File.Open(source, FileMode.Open, FileAccess.Read);

			if (IsFileInUse(source))
			{
				Console.WriteLine("File is use: {0}", source);
				return;
			}
			if (IsFileInUse(destination))
			{
				Console.WriteLine("File is use: {0}", destination);
				return;
			}

			File.Copy(source, destination, true);
			Console.WriteLine("Done");
		}

		static internal bool IsFileInUse(string filename)
		{
			if (!File.Exists(filename))
				return false;

			bool inUse;

			try
			{
				using (File.Open(filename, FileMode.Open, FileAccess.Read, FileShare.None))
				{
					inUse = false;
				}
			}
			catch (IOException )
			{
				inUse = true;
			}

			return inUse;
		}
    }
Gregory
Previous
Next
Reply
Map
View

Click here to load this message in the networking platform