在C#中找出用户名(谁)修改过的文件

时间:2012-07-25 23:31:35

标签: c# file-io event-log filesystemwatcher

我正在使用FileSystemWatcher来监控文件夹。但是当目录中发生某些事件时,我不知道如何搜索谁对该文件产生了影响。我试着使用EventLog。它无法正常工作。还有另一种方法吗?

5 个答案:

答案 0 :(得分:7)

我无法记住我在哪里找到这段代码,但它是使用pInvoke的替代方案,我认为这对于此任务来说有点过分。使用FileSystemWatcher观看文件夹,当事件触发时,您可以使用以下代码确定哪个用户更改了文件:

private string GetSpecificFileProperties(string file, params int[] indexes)
{
    string fileName = Path.GetFileName(file);
    string folderName = Path.GetDirectoryName(file);
    Shell32.Shell shell = new Shell32.Shell();
    Shell32.Folder objFolder;
    objFolder = shell.NameSpace(folderName);
    StringBuilder sb = new StringBuilder();

    foreach (Shell32.FolderItem2 item in objFolder.Items())
    {
        if (fileName == item.Name)
        {
            for (int i = 0; i < indexes.Length; i++)
            {
                sb.Append(objFolder.GetDetailsOf(item, indexes[i]) + ",");
            }

            break;
        }
    }

    string result = sb.ToString().Trim();
    //Protection for no results causing an exception on the `SubString` method
    if (result.Length == 0)
    {
        return string.Empty;
    }
    return result.Substring(0, result.Length - 1);
}

Shell32是对DLL的引用:Microsoft Shell控件和自动化 - 它是一个COM引用

以下是您如何调用该方法的一些示例:

string Type = GetSpecificFileProperties(filePath, 2);
string ObjectKind = GetSpecificFileProperties(filePath, 11);
DateTime CreatedDate = Convert.ToDateTime(GetSpecificFileProperties(filePath, 4));
DateTime LastModifiedDate = Convert.ToDateTime(GetSpecificFileProperties(filePath, 3));
DateTime LastAccessDate = Convert.ToDateTime(GetSpecificFileProperties(filePath, 5));
string LastUser = GetSpecificFileProperties(filePath, 10);
string ComputerName = GetSpecificFileProperties(filePath, 53);
string FileSize = GetSpecificFileProperties(filePath, 1);

答案 1 :(得分:4)

您需要在文件系统上启用审核(审核仅在NTFS上可用)。您可以通过应用组策略或本地安全策略来执行此操作。您还必须对要监视的文件启用审核。您可以像修改文件权限一样执行此操作。

然后将审核事件写入安全事件日志。您必须监视此事件日志以查找您感兴趣的审核事件。一种方法是创建一个计划任务,在您感兴趣的事件被记录时启动应用程序。只有在事件未以非常高的速率记录时,才能为每个事件启动新流程。否则您可能会遇到性能问题。

基本上,您不希望查看文件的内容或属性(shell函数GetFileDetails所执行的操作)。此外,您不希望使用文件共享API来获取打开文件的网络用户(NetGetFileInfo执行此操作)。您想知道上次修改文件的进程的用户。 Windows通常不会记录此信息,因为它需要太多资源才能为所有文件活动执行此操作。相反,您可以选择性地为特定用户执行审核,对特定文件(和文件夹)执行特定操作。

答案 2 :(得分:2)

您似乎需要调用Windows API函数来获取所需内容,这涉及到PInvoke。另一个论坛上的一些人一直在调查它并找出某些东西,你可以找到他们的solution here。但是,它似乎只适用于网络共享上的文件(不在本地计算机上)。

为了将来参考,这是code posted by dave4dl

[DllImport("Netapi32.dll", SetLastError = true)]
static extern int NetApiBufferFree(IntPtr Buffer);

[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto, Pack = 4)]
struct FILE_INFO_3
{
    public int fi3_id;
    public int fi3_permission;
    public int fi3_num_locks;
    public string fi3_pathname;
    public string fi3_username;
}

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

[DllImport("netapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
static extern int NetFileGetInfo(
  string servername,
  int fileid,
  int level,
  ref IntPtr bufptr
);

private int GetFileIdFromPath(string filePath)
{
    const int MAX_PREFERRED_LENGTH = -1;

    int dwReadEntries;
    int dwTotalEntries;
    IntPtr pBuffer = IntPtr.Zero;
    FILE_INFO_3 pCurrent = new FILE_INFO_3();

    int dwStatus = NetFileEnum(null, filePath, null, 3, ref pBuffer, MAX_PREFERRED_LENGTH, out dwReadEntries, out dwTotalEntries, IntPtr.Zero);

    if (dwStatus == 0)
    {
        for (int dwIndex = 0; dwIndex < dwReadEntries; dwIndex++)
        {

            IntPtr iPtr = new IntPtr(pBuffer.ToInt32() + (dwIndex * Marshal.SizeOf(pCurrent)));
            pCurrent = (FILE_INFO_3)Marshal.PtrToStructure(iPtr, typeof(FILE_INFO_3));

            int fileId = pCurrent.fi3_id;

            //because of the path filter in the NetFileEnum function call, the first (and hopefully only) entry should be the correct one
            NetApiBufferFree(pBuffer);
            return fileId;
        }
    }

    NetApiBufferFree(pBuffer);
    return -1;  //should probably do something else here like throw an error
}


private string GetUsernameHandlingFile(int fileId)
{
    string defaultValue = "[Unknown User]";

    if (fileId == -1)
    {
        return defaultValue;
    }

    IntPtr pBuffer_Info = IntPtr.Zero;
    int dwStatus_Info = NetFileGetInfo(null, fileId, 3, ref pBuffer_Info);

    if (dwStatus_Info == 0)
    {
        IntPtr iPtr_Info = new IntPtr(pBuffer_Info.ToInt32());
        FILE_INFO_3 pCurrent_Info = (FILE_INFO_3)Marshal.PtrToStructure(iPtr_Info, typeof(FILE_INFO_3));
        NetApiBufferFree(pBuffer_Info);
        return pCurrent_Info.fi3_username;
    }

    NetApiBufferFree(pBuffer_Info);
    return defaultValue;  //default if not successfull above
}

private string GetUsernameHandlingFile(string filePath)
{
    int fileId = GetFileIdFromPath(filePath);
    return GetUsernameHandlingFile(fileId);
}

答案 3 :(得分:2)

这已经多次讨论过了。我从同一个问题回答:

您不能与FileSystemWatcher异步执行此操作,但是您可以使用文件系统筛选器驱动程序同步执行此操作。该驱动程序允许您获取执行操作的帐户的用户名。

答案 4 :(得分:1)

使用代码posted by dave4dl并更新声明struct FILE_INFO_3如下, 您可以监视创建和更新文件操作的用户名(它类似于FileSystemWatcher和OpenFiles.exe的FileSharing服务器功能的组合)

[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
public struct FILE_INFO_3
{
    public int fi3_id;
    public int fi3_permission;
    public int fi3_num_locks;
    [MarshalAs(UnmanagedType.LPWStr)] 
    public string fi3_pathname;
    [MarshalAs(UnmanagedType.LPWStr)] 
    public string fi3_username;
}

相关问题