C# 使用C关闭打开的文件#
我的情况是,人们连接到共享上的文件,它阻止我覆盖该文件。我正在尝试编写一个方法,查看我提供的文件路径当前是否以这种方式锁定,并关闭此资源的网络会话 我查看了ADSI Winnt提供程序,但没有实现Resources.Remove成员。然后我查看了Win32_ServerSession,虽然我可以使用Delete member,但它会杀死给定用户的所有资源。我需要弄清楚如何更加具体C# 使用C关闭打开的文件#,c#,wmi,C#,Wmi,我的情况是,人们连接到共享上的文件,它阻止我覆盖该文件。我正在尝试编写一个方法,查看我提供的文件路径当前是否以这种方式锁定,并关闭此资源的网络会话 我查看了ADSI Winnt提供程序,但没有实现Resources.Remove成员。然后我查看了Win32_ServerSession,虽然我可以使用Delete member,但它会杀死给定用户的所有资源。我需要弄清楚如何更加具体 P>我一直在寻找关系和财产,但现在我只是被难住了。 很难考虑这么做的所有后果,因为你不一定预测当前文件锁定的应用程
<> P>我一直在寻找关系和财产,但现在我只是被难住了。
很难考虑这么做的所有后果,因为你不一定预测当前文件锁定的应用程序的行为。 还有别的办法吗?例如,您是否必须立即覆盖该文件,或者是否可以让某个外部进程每隔几分钟不断尝试覆盖该文件,直到覆盖成功?
我也遇到了同样的问题。 到目前为止,我知道的唯一方法是使用Win32API: [DllImport("Netapi32.dll", SetLastError=true, CharSet = CharSet.Unicode)] public static extern int NetFileClose(string servername, int id); [DllImport(“Netapi32.dll”,SetLastError=true,CharSet=CharSet.Unicode)] 公共静态外部intnetfileclose(字符串servername,intid); 我做了一个简短的尝试来实现这一点,我可以正确地枚举文件, 但是在我的代码中——我只是查看了一下——关闭一个文件的代码 设置为注释。如果您愿意尝试一下,我可以告诉您发送了一个库[wrapper around NetFileXXX]和一个简短的演示,但是,正如我所说的:我从未关闭过一个文件。但这可能是实现这一目标的捷径 我不知道,现在如何在stackoverflow上交换文件:-(br--mabra您可以使用提供完整文件路径的代码,它将返回锁定该文件的任何内容的
列表:
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;
}
}
或网络计算机:
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();
}
}
}
参考文献:
我会给你一个“不要那样做”的答案:-)我知道我没有给出我为什么需要这样做的原因,但它们是真实的。幸运的是,我把任务交给了其他人。:-)我不知道你是否能做到——如果你能做到,这明智吗?备选方案-你可以通过电子邮件、应用程序等方式向用户发送消息吗?嗨,克里斯。在我看来,在网络上自动部署读/写资源文件总是错误的。我唯一会这样做的情况是,如果文件本身都是只读的设计-但再次作为安装开发人员,我们总是面临“只做它”的心态。我使用C#和FileSystemWatcher实现了一个网络共享文件写入检查器。它从未起作用,因为引发的事件因基线硬件而异。下面是一些细节:实际上这个问题与部署/设置无关。在这种情况下,一个自动构建试图归档到一个已知的文件夹,但有一些被锁定的文件挡住了去路。
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();
}
}
}