2016-12-26 28 views
0

我在嘗試使用.mkv文件(vlc.exe,mpc-hc.exe等)進程的名稱如何找出正在使用哪個進程的文件

我已經設法發現它是否在使用中,但我想知道至關重要的進程正在使用該文件。

我試過了這個帖子How do I find out which process is locking a file using .NET?的建議,但只是插入文件的路徑並運行它似乎沒有工作,它沒有顯示任何進程(我可以運行代碼沒有錯誤)。

public static bool IsFileinUse(FileInfo file) 
{ 
    FileStream stream = null; 

    try 
    { 
     stream = file.Open(FileMode.Open, FileAccess.ReadWrite, FileShare.None); 
    } 
    catch (IOException) 
    { 
     //the file is unavailable because it is: 
     //still being written to 
     //or being processed by another thread 
     //or does not exist (has already been processed) 
     return true; 
    } 
    finally 
    { 
     if (stream != null) 
      stream.Close(); 
    } 
    return false; 
} 
+0

這可以幫助你在正確的方向走http://stackoverflow.com/questions/958123/powershell-script-to-check-an-application-這就是鎖定文件 –

+0

http://stackoverflow.com/questions/317071/how-do-i-find-out-which-process-is-locking-a-file-using-net –

+1

http:// stackoverflow.com/questions/860656/using-c-how-does-one-figure-out-what-process-locked-a-file –

回答

-1

試試這個:

string fileName = @"c:\yourFile.doc";//Path to locked file 

Process tool = new Process(); 
tool.StartInfo.FileName = "handle.exe"; 
tool.StartInfo.Arguments = fileName+" /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(); //kill the process if you want 
} 
+0

什麼是handle.exe? – john

+0

手柄是一個實用程序,顯示有關係統中任何進程的打開手柄的信息。您可以使用它來查看打開文件的程序,或查看程序所有句柄的對象類型和名稱。 – NicoRiff

+0

它是sysinternals工具的一部分...你可以從這裏下載:https://download.sysinternals.com/files/Handle.zip – NicoRiff

相關問題