Ashkan Mobayen Khiabani
Ashkan Mobayen Khiabani

Reputation: 34152

Faulty file in use error

This code is the first code in my Form_Load method:

DirectoryInfo dir =new DirectoryInfo("d:\\themes.thumb");

string[] animals = new string []
{
    "Snakes",
    "SnowyOwls",
    "Tigers",
    "TropicalFish",
    "WildBeauty",
    "Wolves"
};

foreach (FileInfo fil in dir.GetFiles())
{
    for(int ii=0;ii<animals.Length;ii++)
    {
        if (fil.Name.StartsWith(animals[ii]))
        {
        try
        {
            fil.Replace(fil.FullName,fil.FullName.Replace(fil.Name,"Animals-" + fil.Name));
        }
        catch
        {
        }
    }
}

and I'm getting the following error whenever if (fil.Name.StartsWith(animals[ii])) is true:

The process cannot access the file because it is being used by another process.

What is wrong as I have not opened any files before this code?

Upvotes: 1

Views: 53

Answers (3)

sstan
sstan

Reputation: 36473

It looks like you are misunderstanding how to use the FileInfo.Replace method.

fil.Replace(fil.FullName,fil.FullName.Replace(fil.Name,"Animals-" + fil.Name));

Here you are actually trying to overwrite fil's contents with itself. That explains the error message.

You might want to read the documentation a bit more closely.

EDIT: To be absolutely clear: FileInfo.Replace is not meant to be used to perform file renames. It's meant to replace file contents. To perform a rename, you use FileInfo.MoveTo.

Upvotes: 1

nvoigt
nvoigt

Reputation: 77285

You should seperate your reading logic from your update logic.

for example:

var replacements = dir.GetFiles()
                      .Where(file => animals.Any(animal => file.Name.StartsWith(animal)))
                      .Select(file => new 
                                     {
                                       OldFullName = file.FullName, 
                                       NewFullName = file.FullName.Replace(file.Name, "Animals-" + file.Name) 
                                     })
                      .ToList();

foreach (var replacement in replacements)
{
    File.Move(replacement.OldFullName, replacement.NewFullName);
}

Your replace logic has some subtle bugs (what happens with files that are in a folder called "Wolves" for example?) you may wan to work that out.

Upvotes: 1

Zoltan Rajnai
Zoltan Rajnai

Reputation: 1

Get LockHunter. It's a free tool which shows you which process is holding onto a particular file or folder. I found it really useful. Microsoft Process Explorer is also free and can also find open handles (Ctrl+F) by name.

Upvotes: 0

Related Questions