Skip to content

Commit

Permalink
Now ZipExtractor will suggest process that is holding lock on the fil…
Browse files Browse the repository at this point in the history
…e so user can exit from it.
  • Loading branch information
ravibpatel committed Aug 26, 2020
1 parent 974a876 commit cea9029
Show file tree
Hide file tree
Showing 5 changed files with 220 additions and 5 deletions.
Binary file modified AutoUpdater.NET/Resources/ZipExtractor.exe
Binary file not shown.
151 changes: 151 additions & 0 deletions ZipExtractor/FileUtil.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,151 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.InteropServices;

namespace ZipExtractor
{
// https://stackoverflow.com/a/20623302/1273550
public static 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>
public static List<Process> WhoIsLocking(string path)
{
string key = Guid.NewGuid().ToString();
List<Process> processes = new List<Process>();

int res = RmStartSession(out var 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 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 var 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;
}
}
}
44 changes: 40 additions & 4 deletions ZipExtractor/FormMain.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
Expand Down Expand Up @@ -86,7 +87,7 @@ private void FormMain_Shown(object sender, EventArgs e)
#else
// Open an existing zip file for reading.
var zip = ZipStorer.Open(args[1], FileAccess.Read);

// Read the central directory collection.
var entries = zip.ReadCentralDir();
#endif
Expand Down Expand Up @@ -116,12 +117,15 @@ private void FormMain_Shown(object sender, EventArgs e)
bool notCopied = true;
while (notCopied)
{
string filePath = String.Empty;
try
{
#if NET45
entry.ExtractToFile(Path.Combine(path, entry.FullName), true);
filePath = Path.Combine(path, entry.FullName);
entry.ExtractToFile(filePath, true);
#else
zip.ExtractFile(entry, Path.Combine(path, entry.FilenameInZip));
filePath = Path.Combine(path, entry.FilenameInZip);
zip.ExtractFile(entry, filePath);
#endif
notCopied = false;
}
Expand All @@ -132,12 +136,44 @@ private void FormMain_Shown(object sender, EventArgs e)
var errorCode = Marshal.GetHRForException(exception) & 0x0000FFFF;
if (errorCode == errorSharingViolation || errorCode == errorLockViolation)
{
Thread.Sleep(5000);
retries++;
if (retries > MaxRetries)
{
throw;
}

List<Process> lockingProcesses = null;
if (Environment.OSVersion.Version.Major >= 6 && retries >= 2)
{
try
{
lockingProcesses = FileUtil.WhoIsLocking(filePath);
}
catch (Exception)
{
// ignored
}
}

if (lockingProcesses == null)
{
Thread.Sleep(5000);
}
else
{
foreach (var lockingProcess in lockingProcesses)
{
var dialogResult = MessageBox.Show(
string.Format(Resources.FileStillInUseMessage,
lockingProcess.ProcessName, filePath),
Resources.FileStillInUseCaption,
MessageBoxButtons.RetryCancel, MessageBoxIcon.Error);
if (dialogResult == DialogResult.Cancel)
{
throw;
}
}
}
}
else
{
Expand Down
24 changes: 23 additions & 1 deletion ZipExtractor/Properties/Resources.Designer.cs

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 6 additions & 0 deletions ZipExtractor/Properties/Resources.resx
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,12 @@
<data name="CurrentFileExtracting" xml:space="preserve">
<value>Extracting {0}</value>
</data>
<data name="FileStillInUseCaption" xml:space="preserve">
<value>Unable to update the file!</value>
</data>
<data name="FileStillInUseMessage" xml:space="preserve">
<value>{0} is still open and it is using "{1}". Please close the process manually and press Retry.</value>
</data>
<assembly alias="System.Windows.Forms" name="System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
<data name="ZipExtractor" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\Resources\ZipExtractor.png;System.Drawing.Bitmap, System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</value>
Expand Down

0 comments on commit cea9029

Please sign in to comment.