获取被访问文件的用户名

本文关键字:用户 文件 访问 获取 | 更新日期: 2023-09-27 18:11:58

我想获得访问文件的用户名(添加,删除,重命名,…)。实际上,我使用filesystemwatcher来监视文件访问,并且我已经激活了目录上的对象访问,以便通过事件日志获取用户信息。这个解决方案并不完美,因为有很多文件事件,而且事件日志消息不是很详细。写数据只有一个事件id。这是用于添加文件,重命名,移动,…每次写入数据。此外,我必须交叉检查事件日志消息是否与文件系统监视器事件匹配。我想把这件事处理得更好。所以我花了很多时间在谷歌上搜索、阅读……我知道有另一个帖子在stackoverflow

获取打开文件的用户名

但我认为应该有一个可能的解决方案,因为Windows事件可以得到用户名。

阅读几页,我发现应该有一个可能的解决方案使用netapi32.dll。下面的示例代码http://vbcity.com/forums/t/133307.aspx?PageIndex=2对我没用。我无法获得字段,所以我将代码更改为

private ulong GetFileIdFromPath(string filePath)
{
  WinAPI.BY_HANDLE_FILE_INFORMATION objectFileInfo = new WinAPI.BY_HANDLE_FILE_INFORMATION();
  Thread.Sleep(200);
  FileInfo fi = new FileInfo(filePath);
  FileStream fs = fi.Open(FileMode.Open, FileAccess.Read, FileShare.Read);
  WinAPI.GetFileInformationByHandle(fs.Handle, out objectFileInfo);

  fs.Close();

 ulong fileIndex = ((ulong)objectFileInfo.FileIndexHigh << 32) + (ulong)objectFileInfo.FileIndexLow;
  return fileIndex; 
}

使用此代码,我能够获得字段id,但与字段id和示例代码,我无法获得用户名。

获取被访问文件的用户名

从我的上一个程序(2周前)-我被要求审计文件中的更改(也包括用户名)

解决方案是通过文件系统监视程序,并在事件发生后->转到windows的事件日志,然后使用Xpath搜索-查找哪个用户进行了操作。

   public static EventUnit DisplayEventAndLogInformation(string fileToSearch, DateTime actionTime)
        {
            StringBuilder sb = new StringBuilder();
            const string queryString = @"<QueryList>
  <Query Id=""0"" Path=""Security"">
    <Select Path=""Security"">*</Select>
  </Query>
</QueryList>";
            EventLogQuery eventsQuery = new EventLogQuery("Security", PathType.LogName, queryString);
            eventsQuery.ReverseDirection = true;
            EventLogReader logReader = new EventLogReader(eventsQuery);
            EventUnit e = new EventUnit();
            bool isStop = false;
            for (EventRecord eventInstance = logReader.ReadEvent(); null != eventInstance; eventInstance = logReader.ReadEvent())
            {
                foreach (var VARIABLE in eventInstance.Properties)
                    if (VARIABLE.Value.ToString().ToLower().Contains(fileToSearch.ToLower()) && actionTime.ToString("d/M/yyyy HH:mm:ss") == eventInstance.TimeCreated.Value.ToString("d/M/yyyy HH:mm:ss"))
                    {
                        foreach (var VARIABLE2 in eventInstance.Properties) sb.AppendLine(VARIABLE2.Value.ToString());
                        e.Message = sb.ToString();
                        e.User = (eventInstance.Properties.Count > 1) ? eventInstance.Properties[1].Value.ToString() : "n/a";
                        e.File = fileToSearch;
                        isStop = true;
                        break;
                    }
                if (isStop) break;
                try
                {
                    //    Console.WriteLine("Description: {0}", eventInstance.FormatDescription());
                }
                catch (Exception e2)
                {
                }
            }
            return e;
        }