C# Identificar usuario WindowsIdentity

Iniciado por Andrew06, 24 Septiembre 2014, 07:02 AM

0 Miembros y 1 Visitante están viendo este tema.

Andrew06

Hola

Estoy realizando un monitor de eventos en un directorio cuando un archivo es cambiado me realiza una alerta

lo que necesito es identificar que usuario esta realizando el cambio estoy utilizando el siguiente código pero solo me trae el usuario local

WindowsIdentity id = WindowsIdentity.GetCurrent();
string login = id.Name;
Console.WriteLine(login);


Por favor su ayuda con este tema soy un poco nuevo en C Sharp consola de windows

Eleкtro

#1
Con la Class WindowsIdentity no vas a conseguir nada, el método GetCurrent devuelve el usuario local, y debes conocer el nombre del usuario (o el UPN si no formas parte de un dominio) para identificar un usuario usando el Constructor de dicha Class.

Aparte de eso, un FilesystemWatcher no recibe ni devuelve ningún tipo de información sobre el usuario en cuestión, según parece es una tarea bastante compleja de llevar a cabo, tienes mucha información sobre esto en los resultados de Google:

Cita de: http://www.codeproject.com/Questions/769262/How-can-you-obtain-the-username-when-using-a-FileSNTFS doesn't track who deletes, renames, or modifies a file, so there's no way you can get the username. It only keeps track of who OWNS the file.

Cita de: http://stackoverflow.com/questions/8649661/use-the-filesystemwatcher-class-to-document-the-user-who-is-making-changesNo, it's not possible, the NTFS or FAT file system which is what Windows uses doesn't record this information. The best you could get about a file is last time it was changed.

Cita de: http://www.pcreview.co.uk/forums/system-io-filesystemwatcher-class-and-user-identity-t1364792.htmlFirst off, you'll need to devise some way of determining whether the changes to a file were made locally or remotely

Cita de: http://social.msdn.microsoft.com/Forums/vstudio/en-US/77f6f31c-2b0f-48b5-a981-4bcd9f398d9c/vbnet-filesystemwatcher-how-to-return-the-actual-user-who-accessed-the-file?forum=vbgeneralThe only possibilities I can think of would be the NetFileEnum and NetFileGetInfo API function calls

Cita de: http://stackoverflow.com/questions/1286137/which-user-caused-filesystemwatcher-eventsThis isn't currently possible with the current implementations of the FileSystemWatcher as it does not receive this type of information when a file is deleted, or anything about a file changes.
You would need to use Win32 API calls, if it's possible at all. I'm not sure which APIs you would need to use,
but you will end up essentially writing your own version of a file system watcher

Cita de: http://social.msdn.microsoft.com/Forums/vstudio/en-US/77f6f31c-2b0f-48b5-a981-4bcd9f398d9c/vbnet-filesystemwatcher-how-to-return-the-actual-user-who-accessed-the-file?forum=vbgeneralI was looking for the same thing today. I found something that will work.
See here: http://stackoverflow.com/questions/7861512/get-username-of-an-accesed-file

Keep in mind, auditing must be enabled for the folder.




La información de la función NetFileGetInfo es muy escasa así que no puedo mostrarte un ejemplo funcional (tampoco se si funcionaría, solo especulan por internet).
( http://msdn.microsoft.com/en-us/library/windows/desktop/bb525379%28v=vs.85%29.aspx )

Puedes probar la siguiente solución (ya no recuerdo de donde obtuve el código) sacada de: http://stackoverflow.com/questions/11660235/find-out-usernamewho-modified-file-in-c-sharp, pero personalmente y al menos en Windows 8.1 a mi me devuelve el grupo de usuarios (Administradores), no el usuario (Administrador).

La versión en VB.NET
Código (vbnet) [Seleccionar]
Imports System.Text
Imports System.IO

Public Class Form1

   Private Function GetSpecificFileProperties(file As String, ParamArray indexes As Integer()) As String

       Dim fileName As String = Path.GetFileName(file)
       Dim folderName As String = Path.GetDirectoryName(file)
       Dim shell As New Shell32.Shell()
       Dim objFolder As Shell32.Folder
       objFolder = shell.[NameSpace](folderName)
       Dim sb As New StringBuilder()
       For Each item As Shell32.FolderItem2 In objFolder.Items()
           If fileName = item.Name Then
               For i As Integer = 0 To indexes.Length - 1
                   sb.Append(objFolder.GetDetailsOf(item, indexes(i)) + ",")
               Next
               Exit For
           End If
       Next
       Dim result As String = sb.ToString().Trim()
       If result.Length = 0 Then
           Return String.Empty
       End If
       Return result.Substring(0, result.Length - 1)

   End Function

   Private Sub FileSystemWatcher1_Changed(sender As Object, e As FileSystemEventArgs) _
   Handles FileSystemWatcher1.Changed, FileSystemWatcher1.Created

       Dim filepath As String = e.FullPath

       Dim Type As String = GetSpecificFileProperties(filepath, 2)
       Dim ObjectKind As String = GetSpecificFileProperties(filepath, 11)
       Dim CreatedDate As DateTime = Convert.ToDateTime(GetSpecificFileProperties(filepath, 4))
       Dim LastModifiedDate As DateTime = Convert.ToDateTime(GetSpecificFileProperties(filepath, 3))
       Dim LastAccessDate As DateTime = Convert.ToDateTime(GetSpecificFileProperties(filepath, 5))
       Dim LastUser As String = GetSpecificFileProperties(filepath, 10)
       Dim ComputerName As String = GetSpecificFileProperties(filepath, 53)
       Dim FileSize As String = GetSpecificFileProperties(filepath, 1)

       Debug.WriteLine(LastUser)
       Debug.WriteLine(ComputerName)

   End Sub

End Class





Esta parece ser una solución, aunque personalmente no la he consguido hacer funcionar:
http://vbcity.com/forums/p/133307/698930.aspx#698930
+
Cita de: http://stackoverflow.com/questions/11660235/find-out-usernamewho-modified-file-in-c-sharpUse code posted by dave4dl and update declare struct FILE_INFO_3 as following, you can monitor user name of create and update file action(It is like to combination of FileSystemWatcher and OpenFiles.exe's functions of FileSharing Server)
[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;
}

Saludos.