Barakr
Barakr

Reputation: 59

forcing to close a file

I have file that another process using it. and I want to force closing the file. so that I will work on the fill.

I tried to use Handle.exe however it didn't find the process

would appreiciate some help here is my code:

 Process tool = new Process();
            tool.StartInfo.FileName = handlPath;
            tool.StartInfo.Arguments = _pathDirectory + " /accepteula";
            tool.StartInfo.UseShellExecute = false;
            tool.StartInfo.RedirectStandardOutput = true;
            tool.Start();
            tool.WaitForExit();
            string outputTool = tool.StandardOutput.ReadToEnd();

            string matchPattern = @"(?<=\s+pid:\s+)\b(\d+)\b(?=\s+)";
            foreach (Match match in Regex.Matches(outputTool, matchPattern))
            {
                Process.GetProcessById(int.Parse(match.Value)).Kill();
            }

Upvotes: 1

Views: 1502

Answers (2)

astef
astef

Reputation: 9508

I'm sure, that if a program really holds an exclusive access to a file, it has a reason to do it. For example, Windows Explorer holds it when the file is in copying process.

Very often, programs open a file for a writing, but do not actively write to it. For example, when you open a document in MS Word, it is copied to the temp file and a source file is just "open for writing". You'll still have an exception if you use standard File.Open method, but you can copy it to a temp file using File.Copy.

Alternatively, you can explicitly specify FileShare.ReadWrite parameter and get an access to a file. In this case, other program will have problems with accessing a file.

Upvotes: 1

Roshana Pitigala
Roshana Pitigala

Reputation: 8806

If you have mentioned the file name or type it would have been more easier, anyway try using the cmd for this. Get the process name and replace ProcessName.exe of the following code.

First you'll have to add using System.Diagnostics; on top.

Process.Start("cmd.exe", "/c taskkill /F /IM ProcessName.exe");

Upvotes: 0

Related Questions