加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 18:22:35 所属栏目:百科 来源:网络整理
导读:我正在使用FileSystemWatcher来监视文件夹.但是当目录中发生某些事件时,我不知道如何搜索谁对该文件产生了影响.我试着使用EventLog.它无法正常工作.还有另一种方法吗? 解决方法 我不记得我在哪里找到了这个代码,但它是使用pInvoke的替代方案,我觉得这个任务
我正在使用FileSystemWatcher来监视文件夹.但是当目录中发生某些事件时,我不知道如何搜索谁对该文件产生了影响.我试着使用EventLog.它无法正常工作.还有另一种方法吗?

解决方法

我不记得我在哪里找到了这个代码,但它是使用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);

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读