2010-07-15 6 views
1

나는 C# .NET을 사용하여 파일 또는 폴더를 사용하는 다른 프로세스의 이름을 얻을, VS 2008, 나를 위해 .NET 3.5사용중인 파일이나 폴더에 대한 문제 :

, 어렵다, 그러나 나는 샘플 코드가 필요합니다 이것에 대한 C 번호 : 파일이나 폴더가 사용중인 경우 파일이나 폴더를 사용

  • 경우

    1. 는, 프로세스의 이름이 그것을

    ,536,913,632를 사용 확인 10

    예를 들어, 내 문제.

    파일을 삭제하려고하는데 "다른 프로세스에서 사용 중이기 때문에 프로세스가 'XYZ'파일에 액세스 할 수 없습니다." 예외.

    File.Delete(infoFichero.Ruta);

    은 내가 파일을 사용하는 프로세스의 이름을 사용하고, 있는지 확인합니다.

    샘플 코드, 소스 코드가 필요합니다. 나는 C++을 사용하고 싶지 않다. 나는 c, C++, 비 관리 코드 또는 WinApi를 모른다. C# 코드 (관리 코드 .net) 만 사용하고 싶습니다.

    나는 파일을 사용하는 경우

    을 확인하는 방법, 여러 참조를 읽을 수는 있지만 샘플 코드 소스를 얻을하지?

    Emulate waiting on File.Open in C# when file is locked

    http://social.msdn.microsoft.com/Forums/en-US/csharpgeneral/thread/9dabc172-237a-42db-850e-ada08885a5d5

    How to check if a file is in use?

    Easiest way to read text file which is locked by another application

    Using C# is it possible to test if a lock is held on a file

    편집 : 얀 6월에서 - MSFT

    string path = "D:\\temp2.xlsx"; 
          foreach (Process c in Process.GetProcesses()) { 
    
           if (c.MainWindowTitle.Contains(Path.GetFileName(path))){ 
            MessageBox.Show(c.ProcessName); 
            return; 
           } 
          } 
    
          try{ 
           FileInfo f = new FileInfo(path); 
    
           f.Delete(); 
          } 
          catch (Exception ex){ 
    
           MessageBox.Show(ex.Message); 
          } 
    

    ... 그러나 모든 100 % 문제에 대한 해결책을 얻는 것은 어렵습니다.

    1. 문제 : c.MainWindowTitle == null이거나 파일 이름이 없으면 문제가 발생합니다.

    2. 공유 다른 컴퓨터, PC, 서버의 폴더, ... 등에 문제 :

    File.delete를 (@ \ desiis 시간 \ 프로젝트 \의 script.targets \);

    모든 샘플 코드는 도움 전문가, MVP, 누구에게 문의하십시오.

    UPDATE : 폴더

  • +0

    3 명의 사람들이 투표를 할 예정이라면 적어도 그들이 왜 그렇게하고 있는지 말해야합니다. –

    답변

    3

    에 같은 문제는 거기 WINAPI로 스테핑없이, 나는 생각하지 않는다 연 파일이있는 프로세스를 찾을 수있는 방법이 없을거야.그리고 사용 중인지 여부를 확인하는 한, 상태에 연결된 SO 질문과 같이 실제로 할 수있는 유일한 방법은 try/catch 블록에서 파일 액세스 시도를 래핑하는 것입니다.

    어떤 파일을 열 었는지 찾기위한 코드는 추한 것 같지만,이 점을 멋지게 감싼 API가있을 수 있습니다. 제 3 자 유틸리티가 있습니다 (Unlocker이 가장 잘 알려진 예임). ProcessExplorer을 사용하여 열린 파일 핸들을 파일 이름별로 검색 할 수도 있습니다. 그것들은 당신을 정말로 돕지 않습니다.

    내가 여기에 대해 알아 내려고하는 것에 대한 간단한 대답은 이미 링크 된 SO 질문에서 질문의 첫 부분에 대한 대답을 갖고 있고 두 번째 부분에 WIN32 호출이 필요할 것입니다. 피하기 위해 Win32에서 손을 더러워야 할 수도 있습니다 ... 여전히 도움이 필요하십니까?

    편집 : sysinternals Handle 유틸리티로 쉘 아웃 할 수 있습니다. 당신은 그 명령의 출력을 얻고 그것을 직접 파싱 할 필요가있다. 이것은 당신이 라이센스 계약 팝업 당신이 핸들 유틸리티를 처음 실행할 때받을거야입니다 함께이

    string result = proc.StandardOutput.ReadToEnd(); 
    

    문제처럼 실행 프로세스의 출력을 읽을 수 있습니다. 이것이 당신이 배포하기를 희망하는 것이면 전체 라이센스 문제는 말할 것도 없습니다 ...

    만약 당신이 아직도 관심이 있다면, 당신이 어떻게 할 수 있는지 보여줄 수 있습니다.

    EDIT : 파일에 대해 열린 핸들이있는 프로그램의 exe 이름과 PID를 찾는 실행 가능한 프로그램입니다. 나는 주석을 추가했지만 필요한 경우 더 자세히 설명 할 수 있습니다. 여기서는 Regular Expressions를 사용하여 출력을 파싱하여 가장 가까운 작업에서 가장 의미있는 작업을 수행합니다.

    using System; 
    using System.Collections.Generic; 
    using System.Linq; 
    using System.Text; 
    using System.Diagnostics; 
    using System.Text.RegularExpressions; 
    
    namespace ConsoleApplication1 
    { 
        class Program 
        { 
         static void Main(string[] args) 
         { 
          ProcessStartInfo si = new ProcessStartInfo(); 
          si.FileName = "handle.exe";  //name of the handle program from sysinternals 
                  //assumes that its in the exe directory or in your path 
                  //environment variable 
    
          //the following three lines are required to be able to read the output (StandardOutput) 
          //and hide the exe window. 
          si.RedirectStandardOutput = true; 
          si.WindowStyle = ProcessWindowStyle.Hidden; 
          si.UseShellExecute = false; 
    
          si.Arguments = "test.xlsx";  //this is the file you're trying to access that is locked 
    
          //these 4 lines create a process object, start it, then read the output to 
          //a new string variable "s" 
          Process p = new Process(); 
          p.StartInfo = si; 
          p.Start(); 
          string s = p.StandardOutput.ReadToEnd(); 
    
          //this will use regular expressions to search the output for process name 
          //and print it out to the console window 
          string regex = @"^\w*\.EXE"; 
          MatchCollection matches = Regex.Matches(s, regex, RegexOptions.Multiline); 
          foreach (var match in matches) 
          { 
           Console.WriteLine(match); 
          } 
    
          //this will use regex to search the output for the process id (pid) 
          //and print it to the console window. 
          regex = @"pid: (?<pid>[0-9]*)"; 
          matches = Regex.Matches(s, regex, RegexOptions.Multiline); 
          foreach (var obj in matches) 
          { 
           Match match = (Match)obj; //i have to cast to a Match object 
                  //to be able to get the named group out 
           Console.WriteLine(match.Groups["pid"].Value.ToString()); 
          } 
    
          Console.Read(); 
         } 
        } 
    } 
    
    +0

    팀 코커, 나는 아직도 관심이 있습니다. 만약 당신이 어떻게 할 수 있는지 보여 주실 수 있습니다. 감사 – Kiquenet

    1

    이렇게하는 방법은 없습니다. P/invoke 또는 유사한 API를 사용하여 저수준 API를 사용해야합니다.

    좋은 방법이 있지만 여기에는 C++ 코드가 있습니다. 너 스스로 이식해야 해.

    http://www.codeproject.com/KB/shell/OpenedFileFinder.aspx

    참고이 몇 가지 복잡한 문제, 커널 대 사용자 공간 메모리 주위 즉 문제가 있습니다. 이것은 해결하려는 간단한 문제가 아닙니다.

    관련 문제