简体   繁体   中英

C# Cannot Delete File - System.UnauthorizedAccessException

I am running a separate process that minimizes a folder of javascript files. This process creates a new file for each of the js files with "_min.js" appended to it. The next step is to delete the old js files (the ones without "_min.js"). For some reason File.Delete cannot delete these files.

It would appear that some process still has a handle on these files. I get a System.UnauthorizedAccessException exception when I attempt the delete. I have sufficient privileges to this folder. Can someone tell me what I am overlooking?

I am running the process several times in this loop.

 foreach (var fileInfo in jsFiles)
            {
                var outFileName = fileInfo.FullName.Replace(".js", "_min.js");

                var compressorPath = "\"C:\\Dev\\Team Interactive Tools\\trunk\\Infrastructure\\MsBuild\\lib\\yuicompressor-2.4.2.jar\"";
               StringBuilder stringBuilder = new StringBuilder("-jar " + compressorPath + " ");
               stringBuilder.Append("\"" + fileInfo.FullName + "\"");
               stringBuilder.Append(" -o " + "\"" + outFileName + "\"");

                Process p = new Process();
                p.StartInfo.FileName = "\"C:\\Program Files (x86)\\Java\\jre6\\bin\\java\"";
                p.StartInfo.Arguments = stringBuilder.ToString();
                p.StartInfo.UseShellExecute = false;
                p.StartInfo.RedirectStandardOutput = true;
                p.Start();

            }

            return true;
        }

Then I try to remove the orginals:

   private void RemoveOrginalJs(FileInfo[] files)
    {
        foreach (var fileInfo in files)
        {
                File.Delete(fileInfo.FullName);
        }
    }

I am tried Process.close() after each process run but it makes no differance.

I don't know the tool that you are starting, but waiting for its completion somehow seems the right thing to do:

p.Start();
p.WaitForExit();

Maybe the threads still have the file locked? Do you wait for them to finish before you try and delete?

Try Process.Kill() and delete afterwards.
Further you have to check if the script isn't running in another process aswell. To determinate this, try using Unlocker .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM