您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

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

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

我不记得我在哪里找到了这段代码,但是它是使用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 Controls and Automation-

这是有关如何调用方法的一些示例:

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);

或将多个逗号分隔的属性放在一起:

string SizeTypeAndLastModDate = GetSpecificFileProperties(filePath, new int[] {1, 2, 3});

注意:此解决方案已在Windows 7和Windows 10上进行了测试。除非使用Shell32获取文件扩展属性时按照Except455 STA上运行,否则该解决方案将无法工作,并且您将看到以下错误

无法将类型为“ Shell32.ShellClass”的COM对象转换为接口类型为“ Shell32.IShellDispatch6”

c# 2022/1/1 18:14:08 有566人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶