Bob
Bob

Reputation: 387

C# access error when deleting a file

Using c# when I copy a bat file (File.Copy()) from one location to another on my C drive and close the program then run another program and try delete the file (File.Delete()) I get an error: Access to the path 'C:...\file.bat' is denied.

So i'm thinking it's a permission issue on the oroginal file.

But then I run a program that creates a file (File.Create()), close the program and go to properties on the 2 file and look at the security tab and the permissions are exactly the same!

When I run a program to delete the second file i don't get an error. So why do i get the error on the file the was created using File.Copy?

Upvotes: 0

Views: 693

Answers (4)

Bob
Bob

Reputation: 387

Ah, when I do: File.SetAttributes(@"C:...bat", FileAttributes.Normal);

I can then delete!

Thanks all

Upvotes: 2

smirkingman
smirkingman

Reputation: 6368

This can happen if you close your C# program abruptly, without it closing the file (or it never closed the file). In this case, the file is 'in use', and the message can sometimes be interpreted as a security problem.

Upvotes: 0

Aliostad
Aliostad

Reputation: 81660

Important to know if you

1) are using windows 7 or Vista and file is located in a location which requires admininstrator access for deleting it.

2) If you run those apps under different identity e.g. one is server

3) Location of the files

4) Special access set on the original file which is copied across

Upvotes: 0

Shyju
Shyju

Reputation: 218732

If you are sure that you have enough permission to delete the file,I doubt the problem is like, you are trying to delete the file when the file is still open or still in some process.So make sure that the file is not open and it's free from all other processes when you call the File.Delete method

Upvotes: 2

Related Questions