Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Files protected for no reason

Status
Not open for further replies.

stillinlife101

Programmer
Feb 15, 2005
29
0
0
US
I get the error: "The process cannot access the file 'cust.001' because it is being used by another process." When I run the following code:

Code:
DirectoryInfo di = new DirectoryInfo(Path + "\\customers\\");
FileInfo[] fi = di.GetFiles("cust.*");
int[] b;
foreach (FileInfo f in fi)
   f.Delete();

However, the files will delete just fine with this code:

Code:
DirectoryInfo di = new DirectoryInfo(Path + "\\customers\\");
FileInfo[] fi = di.GetFiles("cust.*");
//int[] b;
foreach (FileInfo f in fi)
   f.Delete();

Why would declaring a variable array make a difference?

Dan
 
Both cases should run fine. The line will not cause anything like failure of the code...if you are not using 'b' in later part of your code, then it will be a warning.
If you want to check what exactly is locking the file, run the following tool after executing your first code.
Who lock me

Sharing the best from my side...

--Prashant--
 
It gets stranger and stranger. int[] b is not used anywhere at all. In the actual code there is a different array declaration, and I stripped down the code to see what was actually causing the error, and it turns out that if I declare a variable there--doesn't even matter if it's an array--the code gives me the "The process cannot access the file 'cust.001' because it is being used by another process." error.

But wait. There's more. I downloaded the program you linked and tried it, but it came up with nothing. So I tried deleting the file, and it worked fine. So why does my program think it's locked?

Dan
 
Did you check whether that file is not opened by any means...through your code or by explorer?

Sharing the best from my side...

--Prashant--
 
If your program ever opened or inspected the file, the object instance you used (stream or other I/O class) may not have been garbage collected yet. Wrapper your file I/O in it's own class, and have that class implement the IDisposable pattern. When you're done with using your instance of that class, call the .Dispose method to ensure that the unmanaged resources (like file handles!) get freed.

Chip H.


____________________________________________________________________
If you want to get the best response to a question, please read FAQ222-2244 first
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top