使用C#强制关闭Windows Server 2012上的开放网络文件

时间:2016-11-07 06:21:37

标签: c# file windows-server-2012-r2

有没有办法强制关闭Server 2012上特定文件的任何实例?

为了论证,请调用文件D:\Shares\Shared\Sharedfile.exe

的链接

我有C#代码,它将最新版本的程序复制到此目录中,该目录通常会让人们在白天使用该程序。关闭打开的文件句柄并替换文件效果很好,因为它只是意味着用户下次打开程序时会有所有最新的更改。

然而,从服务器上的计算机管理来看这有点单调,所以我想知道是否有办法从C#代码中做到这一点?

我试过这个,但它没有我需要的正确重载。也许我可以使用的File课程中有什么东西?

编辑关闭文件的C#代码将 NOT 在主机服务器上运行。

[DllImport("Netapi32.dll", SetLastError=true, CharSet = CharSet.Unicode)]
public static extern int NetFileClose(string servername, int id);

1 个答案:

答案 0 :(得分:2)

您可以打包NetFileClose API,这也需要包装NetFileEnum API。像这样:

[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
struct FILE_INFO_3 {
    public int fi3_id;
    public int fi3_permissions;
    public int fi3_num_locks;
    public string fi3_pathname;
    public string fi3_username;
}

static class NativeMethods {
    [DllImport("netapi32.dll", CharSet = CharSet.Unicode)]
    public extern static int NetFileEnum(
        string servername, 
        string basepath, 
        string username, 
        int level, 
        out IntPtr bufptr, 
        int prefmaxlen, 
        out int entriesread, 
        out int totalentries, 
        ref IntPtr resume_handle
    );

    [DllImport("netapi32.dll", CharSet = CharSet.Unicode)]
    public extern static int NetFileClose(string servername, int fileid);

    [DllImport("netapi32.dll")]
    public extern static int NetApiBufferFree(IntPtr buffer);
}

非常丑陋的签名,对吗?让我们围绕它进行一点点管理。

class RemoteFile {
    public RemoteFile(string serverName, int id, string path, string userName) {
        ServerName = serverName;
        Id = id;
        Path = path;
        UserName = userName;
    }
    public string ServerName { get; }
    public int Id { get; }
    public string Path { get; }
    public string UserName { get; }

    public void Close() {
        int result = NativeMethods.NetFileClose(ServerName, Id);
        if (result != 0) {
            // handle error decently, omitted for laziness
            throw new Exception($"Error: {result}");
        }
    }
}

IEnumerable<RemoteFile> EnumRemoteFiles(string serverName, string basePath = null) {
    int entriesRead;
    int totalEntries;
    IntPtr resumeHandle = IntPtr.Zero;
    IntPtr fileEntriesPtr = IntPtr.Zero;
    try {
        int result = NativeMethods.NetFileEnum(
            servername: serverName,
            basepath: basePath, 
            username: null, 
            level: 3, 
            bufptr: out fileEntriesPtr, 
            prefmaxlen: -1, 
            entriesread: out entriesRead, 
            totalentries: out totalEntries, 
            resume_handle: ref resumeHandle
        );
        if (result != 0) {
            // handle error decently, omitted for laziness
            throw new Exception($"Error: {result}");
        }
        for (int i = 0; i != entriesRead; ++i) {
            FILE_INFO_3 fileInfo = (FILE_INFO_3) Marshal.PtrToStructure(
                fileEntriesPtr + i * Marshal.SizeOf(typeof(FILE_INFO_3)), 
                typeof(FILE_INFO_3)
            );
            yield return new RemoteFile(
                serverName, 
                fileInfo.fi3_id, 
                fileInfo.fi3_pathname, 
                fileInfo.fi3_username
            );
        }
    } finally {
        if (fileEntriesPtr != IntPtr.Zero) {
            NativeMethods.NetApiBufferFree(fileEntriesPtr);
        }
    }
}

现在关闭特定文件很简单:关闭它的所有打开实例。

foreach (var file in EnumRemoteFiles(server, path)) {
    Console.WriteLine($"Closing {file.Path} at {file.ServerName} (opened by {file.UserName})");
    file.Close();
}

请注意,此代码还没有完全准备就绪,特别是错误处理很糟糕。此外,在我的测试中,看起来文件路径可能会受到一些损坏,具体取决于它们是如何打开的(如文件显示为C:\\Path\File,在驱动器根目录后有一个额外的反斜杠)所以你可能想要在验证名称之前进行规范化。不过,这仍然可以解决问题。