C#을 사용하여 다른 프로세스에 의해 잠긴 파일을 삭제하는 방법을 찾고 있습니다. 이 방법은 파일을 잠그고있는 프로세스를 찾은 다음 (아마도 핸들을 추적하여 찾을 수 있지만 C#에서이 작업을 수행하는 방법을 잘 모르겠지만) 해당 프로세스를 닫은 다음 File.Delete()
를 사용하여 파일 삭제를 완료 할 수 있어야한다고 생각합니다.
다른 프로세스를 죽이는 것은 바람직하지 않습니다. 제거와 같은 시나리오가 포함된 경우, MoveFileEx
API 함수를 사용하여 다음 재부팅 시 파일을 삭제하도록 표시할 수 있습니다.
다른 프로세스에서 사용 중인 파일을 삭제해야 하는 경우, 해결책을 고려하기 전에 실제 문제를 다시 고려하는 것이 좋습니다.
일반적인 방법은 다음과 같습니다. # 39, ve you& 할 때는 이 여기에서 C # 의 댁이라면 것 "이라고 말했다.
기본적으로: 잠금을 해제할 수 있는 방법을 제시해 " locked"; 잘못된 # 39 를 투입할 수 있는 파일은 DLL 파일을 process& 의 주소 공간과 닫으십시오 구하겠죠 기본 또는 관리되는 코드를 사용하여 이를 수행할 수 있습니다. # 39, re, you& 아무리 적은 양의 원시 코드 또는 P / Invoke 더 이상 필요 이상의 꽂으십시오 마찬가지다.
도움됐네 링크:
굿 럭!
프로그래밍 방식으로 하고 싶다면. 잘 모르겠지만... 정말 추천하고 싶지 않다. 자신의 컴퓨터에서 문제를 해결하려는 경우 SysInternals Process Explorer가 도움이 될 수 있습니다.
이 프로그램을 실행하고 핸들 찾기 명령(찾기 또는 핸들 메뉴에 있는 것 같습니다)을 사용하여 파일 이름을 검색합니다. 핸들을 찾으면 강제로 닫을 수 있습니다.
그런 다음 파일을 삭제하는 등의 작업을 할 수 있습니다.
주의, 이렇게 하면 속담에 나오는 양탄자 밑에서 양탄자를 꺼낸 것처럼 핸들을 소유한 프로그램이 이상하게 동작할 수 있지만, 잘못된 코드를 디버깅할 때나 비주얼 스튜디오/윈도우 탐색기가 엉망이어서 오래 전에 파일을 닫으라고 했는데도 파일 핸들을 해제하지 않을 때 잘 작동합니다... 한숨이 절로 나온다 :-)
이 프로그램인 Handle을 사용하여 파일에 잠금이 걸려있는 프로세스를 찾을 수 있습니다. 명령 줄 도구이므로 그 출력을 사용하는 것 같습니다. 프로그래밍 방식으로 찾는 방법은 잘 모르겠습니다.
파일 삭제가 지연될 수 있다면 다음에 컴퓨터를 시작할 때 삭제하도록 지정할 수 있습니다:
REGEDT32 (W2K)또는
REGEDIT (WXP)`를 시작하고 다음으로 이동합니다:
HKEY_LOCAL_MACHINE\시스템\현재제어설정\제어\세션 관리자
W2K 및 WXP
W2K:
편집
값 추가...
데이터 유형: REG_MULTI_SZ
값 이름: PendingFileRenameOperations
OK
WXP:
편집
새
다중 문자열 값
엔터
PendingFileRenameOperations
데이터 영역에 삭제할 \???\" + 파일명
을 입력합니다. LFN은
을 따옴표로 묶지 않고 입력할 수 있습니다. C:\장소명\장소명 파일명.exe`를 삭제하려면 다음 데이터를 입력합니다:
\???\C:\긴 디렉터리 이름\긴 파일 이름.exe
그런 다음 확인 키를 누릅니다.
W2K:
편집
바이너리
데이터 형식 선택: Hex
16진수 문자열 끝을 클릭하고
0000(0 네 개)를 입력합니다
kbd>확인
(후손을 위해 어떤 임의의 포럼에서 뻔뻔하게 훔쳤습니다.)(후손을 위해.)
오리온 에드워즈 조언을 통해 내가 다운로드했습니다 시스인터널스 Process&, nbsp, Explorer 에서 해당 파일을 삭제하는 데 어려움을 겪고 있는 나를 발견할 수 있었는데 선반가공 허용됩니까 롬폭 대답하도다 억류되어 있는 것이 아니라, '뒤에' 렉셀리아프리카티언스 생각해봤죠 객체에는 없는 사실을 만들어 내 메일을 보낼 수 있는 코드를 C # 코드가 인도하심이라만일 부착품 객체에는 왼쪽 핸들 이 fileopen.
내가 본 후, 나는 이 매우 간단한 방법을 첨부 파일 핸들 객체에는 처리를 요구했다 발매되었다.
이 날 함께 사용할 수 있는 시스인터널스 explorer 발견하십시오 Visual& Studio&, 디버거, 2005년, 빨리, 빨리.
내가 이 도구를 것을 권장합니다!
날 위해 예약했놨나. 파일 핸들 서있느라 방법입니다.
http://www.timstall.com/2009/02/killing-file-handles-but-not-process.html
전체 파일 경로를 제공할 수 있는 코드를 사용할 수 있습니다, 정보기술 (it), 'a', '어떤 것도 반환되므로 list< processes> 잠금식 해당 파일:
using System.Runtime.InteropServices;
using System.Diagnostics;
static public class FileUtil
{
[StructLayout(LayoutKind.Sequential)]
struct RM_UNIQUE_PROCESS
{
public int dwProcessId;
public System.Runtime.InteropServices.ComTypes.FILETIME ProcessStartTime;
}
const int RmRebootReasonNone = 0;
const int CCH_RM_MAX_APP_NAME = 255;
const int CCH_RM_MAX_SVC_NAME = 63;
enum RM_APP_TYPE
{
RmUnknownApp = 0,
RmMainWindow = 1,
RmOtherWindow = 2,
RmService = 3,
RmExplorer = 4,
RmConsole = 5,
RmCritical = 1000
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
struct RM_PROCESS_INFO
{
public RM_UNIQUE_PROCESS Process;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = CCH_RM_MAX_APP_NAME + 1)]
public string strAppName;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = CCH_RM_MAX_SVC_NAME + 1)]
public string strServiceShortName;
public RM_APP_TYPE ApplicationType;
public uint AppStatus;
public uint TSSessionId;
[MarshalAs(UnmanagedType.Bool)]
public bool bRestartable;
}
[DllImport("rstrtmgr.dll", CharSet = CharSet.Unicode)]
static extern int RmRegisterResources(uint pSessionHandle,
UInt32 nFiles,
string[] rgsFilenames,
UInt32 nApplications,
[In] RM_UNIQUE_PROCESS[] rgApplications,
UInt32 nServices,
string[] rgsServiceNames);
[DllImport("rstrtmgr.dll", CharSet = CharSet.Auto)]
static extern int RmStartSession(out uint pSessionHandle, int dwSessionFlags, string strSessionKey);
[DllImport("rstrtmgr.dll")]
static extern int RmEndSession(uint pSessionHandle);
[DllImport("rstrtmgr.dll")]
static extern int RmGetList(uint dwSessionHandle,
out uint pnProcInfoNeeded,
ref uint pnProcInfo,
[In, Out] RM_PROCESS_INFO[] rgAffectedApps,
ref uint lpdwRebootReasons);
/// <summary>
/// Find out what process(es) have a lock on the specified file.
/// </summary>
/// <param name="path">Path of the file.</param>
/// <returns>Processes locking the file</returns>
/// <remarks>See also:
/// http://msdn.microsoft.com/en-us/library/windows/desktop/aa373661(v=vs.85).aspx
/// http://wyupdate.googlecode.com/svn-history/r401/trunk/frmFilesInUse.cs (no copyright in code at time of viewing)
///
/// </remarks>
static public List<Process> WhoIsLocking(string path)
{
uint handle;
string key = Guid.NewGuid().ToString();
List<Process> processes = new List<Process>();
int res = RmStartSession(out handle, 0, key);
if (res != 0) throw new Exception("Could not begin restart session. Unable to determine file locker.");
try
{
const int ERROR_MORE_DATA = 234;
uint pnProcInfoNeeded = 0,
pnProcInfo = 0,
lpdwRebootReasons = RmRebootReasonNone;
string[] resources = new string[] { path }; // Just checking on one resource.
res = RmRegisterResources(handle, (uint)resources.Length, resources, 0, null, 0, null);
if (res != 0) throw new Exception("Could not register resource.");
//Note: there's a race condition here -- the first call to RmGetList() returns
// the total number of process. However, when we call RmGetList() again to get
// the actual processes this number may have increased.
res = RmGetList(handle, out pnProcInfoNeeded, ref pnProcInfo, null, ref lpdwRebootReasons);
if (res == ERROR_MORE_DATA)
{
// Create an array to store the process results
RM_PROCESS_INFO[] processInfo = new RM_PROCESS_INFO[pnProcInfoNeeded];
pnProcInfo = pnProcInfoNeeded;
// Get the list
res = RmGetList(handle, out pnProcInfoNeeded, ref pnProcInfo, processInfo, ref lpdwRebootReasons);
if (res == 0)
{
processes = new List<Process>((int)pnProcInfo);
// Enumerate all of the results and add them to the
// list to be returned
for (int i = 0; i < pnProcInfo; i++)
{
try
{
processes.Add(Process.GetProcessById(processInfo[i].Process.dwProcessId));
}
// catch the error -- in case the process is no longer running
catch (ArgumentException) { }
}
}
else throw new Exception("Could not list processes locking resource.");
}
else if (res != 0) throw new Exception("Could not list processes locking resource. Failed to get size of result.");
}
finally
{
RmEndSession(handle);
}
return processes;
}
}
그런 다음 그들을 는 프로세스 목록 및 닫기의 삭제하시겠습니까 파일:
string[] files = Directory.GetFiles(target_dir);
List<Process> lstProcs = new List<Process>();
foreach (string file in files)
{
lstProcs = ProcessHandler.WhoIsLocking(file);
if (lstProcs.Count > 0) // deal with the file lock
{
foreach (Process p in lstProcs)
{
if (p.MachineName == ".")
ProcessHandler.localProcessKill(p.ProcessName);
else
ProcessHandler.remoteProcessKill(p.MachineName, txtUserName.Text, txtPassword.Password, p.ProcessName);
}
File.Delete(file);
}
else
File.Delete(file);
}
따라 켜있을 파일의 경우 로컬 컴퓨터:
public static void localProcessKill(string processName)
{
foreach (Process p in Process.GetProcessesByName(processName))
{
p.Kill();
}
}
또는 네트워크 컴퓨터:
public static void remoteProcessKill(string computerName, string fullUserName, string pword, string processName)
{
var connectoptions = new ConnectionOptions();
connectoptions.Username = fullUserName; // @"YourDomainName\UserName";
connectoptions.Password = pword;
ManagementScope scope = new ManagementScope(@"\\" + computerName + @"\root\cimv2", connectoptions);
// WMI query
var query = new SelectQuery("select * from Win32_process where name = '" + processName + "'");
using (var searcher = new ManagementObjectSearcher(scope, query))
{
foreach (ManagementObject process in searcher.Get())
{
process.InvokeMethod("Terminate", null);
process.Dispose();
}
}
}
https://stackoverflow.com/questions/41841590/delete-a-directory-where-someone-has-opened-a-file
아, 내가 년전인데다 도래하도록하려하는 indows won& # 39, 하나의 큰 해킹 취업자 수는 없는 파일 삭제 저들이요 않지만, 이동할 수 있습니다.
정렬하려면 dtep 코드:
mv %WINDIR%\System32\mfc42.dll %WINDIR\System32\mfc42.dll.old
Install new mfc42.dll
Tell user to save work and restart applications
이 때 애플리케이션과도 재시작될 (참고 저희에게는힘과 didn& 재부팅하십시오 # 39, t need to machine) 을, 그들은 새로운 'mfc42.dll 로드되었는지', 그리고 이 모든 것. 함께 한 다음에 삭제할 수 있는 '이전' 펜딩필레오페라티온스 시스템 전체를 놓고 다니라는데 협력했습니다 재시작될, 뭐.