четверг, 31 мая 2012 г.

Get special folders icons (images) using C#




public class SpecialFolderIconSample      
{
 [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
        private struct SHFILEINFO
        {
            public IntPtr hIcon;
            public int iIcon;
            public uint dwAttributes;
            [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]
            public string szDisplayName;
            [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 80)]
            public string szTypeName;
        };

        [DllImport("shell32.dll", CharSet = CharSet.Auto)]
        private static extern IntPtr SHGetFileInfo(IntPtr pszPath, uint dwFileAttributes, out SHFILEINFO psfi, uint cbFileInfo, int uFlags);

        [DllImport("user32.dll", SetLastError = true)]
        [return: MarshalAs(UnmanagedType.Bool)]
        private static extern bool DestroyIcon(IntPtr hIcon);

        [DllImport("shell32.dll", SetLastError = true)]
        private static extern int SHGetSpecialFolderLocation(IntPtr hwndOwner, CSIDL nFolder, ref IntPtr ppidl);

        [DllImport("shell32.dll", SetLastError = true)]
        [return: MarshalAs(UnmanagedType.Bool)]
        private static extern bool SHGetPathFromIDListW(IntPtr pidl, [MarshalAs(UnmanagedType.LPTStr)] StringBuilder pszPath);

        private enum CSIDL
        {
            CSIDL_DESKTOP = 0x0000,    // <desktop>
            CSIDL_INTERNET = 0x0001,    // Internet Explorer (icon on desktop)
            CSIDL_PROGRAMS = 0x0002,    // Start Menu\Programs
            CSIDL_CONTROLS = 0x0003,    // My Computer\Control Panel
            CSIDL_PRINTERS = 0x0004,    // My Computer\Printers
            CSIDL_PERSONAL = 0x0005,    // My Documents
            CSIDL_FAVORITES = 0x0006,    // <user name>\Favorites
            CSIDL_STARTUP = 0x0007,    // Start Menu\Programs\Startup
            CSIDL_RECENT = 0x0008,    // <user name>\Recent
            CSIDL_SENDTO = 0x0009,    // <user name>\SendTo
            CSIDL_BITBUCKET = 0x000a,    // <desktop>\Recycle Bin
            CSIDL_STARTMENU = 0x000b,    // <user name>\Start Menu
            CSIDL_MYDOCUMENTS = 0x000c,    // logical "My Documents" desktop icon
            CSIDL_MYMUSIC = 0x000d,    // "My Music" folder
            CSIDL_MYVIDEO = 0x000e,    // "My Videos" folder
            CSIDL_DESKTOPDIRECTORY = 0x0010,    // <user name>\Desktop
            CSIDL_DRIVES = 0x0011,    // My Computer
            CSIDL_NETWORK = 0x0012,    // Network Neighborhood (My Network Places)
            CSIDL_NETHOOD = 0x0013,    // <user name>\nethood
            CSIDL_FONTS = 0x0014,    // windows\fonts
            CSIDL_TEMPLATES = 0x0015,
            CSIDL_COMMON_STARTMENU = 0x0016,    // All Users\Start Menu
            CSIDL_COMMON_PROGRAMS = 0X0017,    // All Users\Start Menu\Programs
            CSIDL_COMMON_STARTUP = 0x0018,    // All Users\Startup
            CSIDL_COMMON_DESKTOPDIRECTORY = 0x0019,    // All Users\Desktop
            CSIDL_APPDATA = 0x001a,    // <user name>\Application Data
            CSIDL_PRINTHOOD = 0x001b,    // <user name>\PrintHood
            CSIDL_LOCAL_APPDATA = 0x001c,    // <user name>\Local Settings\Applicaiton Data (non roaming)
            CSIDL_ALTSTARTUP = 0x001d,    // non localized startup
            CSIDL_COMMON_ALTSTARTUP = 0x001e,    // non localized common startup
            CSIDL_COMMON_FAVORITES = 0x001f,
            CSIDL_INTERNET_CACHE = 0x0020,
            CSIDL_COOKIES = 0x0021,
            CSIDL_HISTORY = 0x0022,
            CSIDL_COMMON_APPDATA = 0x0023,    // All Users\Application Data
            CSIDL_WINDOWS = 0x0024,    // GetWindowsDirectory()
            CSIDL_SYSTEM = 0x0025,    // GetSystemDirectory()
            CSIDL_PROGRAM_FILES = 0x0026,    // C:\Program Files
            CSIDL_MYPICTURES = 0x0027,    // C:\Program Files\My Pictures
            CSIDL_PROFILE = 0x0028,    // USERPROFILE
            CSIDL_SYSTEMX86 = 0x0029,    // x86 system directory on RISC
            CSIDL_PROGRAM_FILESX86 = 0x002a,    // x86 C:\Program Files on RISC
            CSIDL_PROGRAM_FILES_COMMON = 0x002b,    // C:\Program Files\Common
            CSIDL_PROGRAM_FILES_COMMONX86 = 0x002c,    // x86 Program Files\Common on RISC
            CSIDL_COMMON_TEMPLATES = 0x002d,    // All Users\Templates
            CSIDL_COMMON_DOCUMENTS = 0x002e,    // All Users\Documents
            CSIDL_COMMON_ADMINTOOLS = 0x002f,    // All Users\Start Menu\Programs\Administrative Tools
            CSIDL_ADMINTOOLS = 0x0030,    // <user name>\Start Menu\Programs\Administrative Tools
            CSIDL_CONNECTIONS = 0x0031,    // Network and Dial-up Connections
            CSIDL_COMMON_MUSIC = 0x0035,    // All Users\My Music
            CSIDL_COMMON_PICTURES = 0x0036,    // All Users\My Pictures
            CSIDL_COMMON_VIDEO = 0x0037,    // All Users\My Video
            CSIDL_CDBURN_AREA = 0x003b    // USERPROFILE\Local Settings\Application Data\Microsoft\CD Burning
        }

        private BitmapImage GetFolderIcon(CSIDL csidl)
        {
            var shfi = new SHFILEINFO();

            IntPtr ptrDir = IntPtr.Zero;
            SHGetSpecialFolderLocation(IntPtr.Zero, csidl, ref ptrDir);

            var res = SHGetFileInfo(ptrDir, 0, out shfi, (uint)Marshal.SizeOf(shfi), 0x000000100 | 0x000000008);

            Marshal.FreeCoTaskMem(ptrDir);


            var icon = (Icon)System.Drawing.Icon.FromHandle(shfi.hIcon).Clone();

            DestroyIcon(shfi.hIcon);

            Bitmap bmp = icon.ToBitmap();

            using (MemoryStream strm = new MemoryStream())
            {
                bmp.Save(strm, System.Drawing.Imaging.ImageFormat.Png);

                BitmapImage bmpImage = new BitmapImage();

                bmpImage.BeginInit();
                bmpImage.CacheOption = BitmapCacheOption.OnLoad;
                strm.Seek(0, SeekOrigin.Begin);
                bmpImage.StreamSource = strm;
                bmpImage.EndInit();

                bmpImage.Freeze();

                return bmpImage;
            }
        }

        private string GetFolderPath(CSIDL csidl)
        {
            IntPtr ptrDir = IntPtr.Zero;

            try
            {
                const int MAX_PATH = 260;

                SHGetSpecialFolderLocation(IntPtr.Zero, csidl, ref ptrDir);

                StringBuilder sbDirVideo = new StringBuilder(MAX_PATH);

                if (SHGetPathFromIDListW(ptrDir, sbDirVideo))
                {
                    return sbDirVideo.ToString();
                }
            }
            finally
            {
                Marshal.FreeCoTaskMem(ptrDir);
            }

            return null;
        }

public void LoopSpecialFolders()
{
foreach (var specialFolder in Enum.GetNames(typeof(CSIDL)).OrderBy(f => f))

            {
                var f = specialFolder;

                var sfi = new SystemFolderInfo
                    {
                        FolderName = f.Substring(f.IndexOf("_") + 1),
                        Path = GetFolderPath((CSIDL)Enum.Parse(typeof(CSIDL), f)),
                        Icon = GetFolderIcon((CSIDL)Enum.Parse(typeof(CSIDL), f))
                    };
            }

}
}


ListView autogenerate columns and sort on header click wpf mvvm

In XAML:

<ViewModel:ListViewEx IsSortable="True" ItemsSource="{Binding Items}" SelectedItem="{Binding SelectedItem}"  AutoGenerateColumns="True" />


using System;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Data;
using System.Windows.Media.Imaging;



public class ListViewEx : ListView
    {
        public bool AutoGenerateColumns
        {
            get { return (bool)GetValue(AutoGenerateColumnsProperty); }
            set { SetValue(AutoGenerateColumnsProperty, value); }
        }

        public bool IsSortable
        {
            get { return (bool)GetValue(IsSortableProperty); }
            set { SetValue(IsSortableProperty, value); }
        }

        public static readonly DependencyProperty AutoGenerateColumnsProperty =
            DependencyProperty.Register("AutoGenerateColumns", typeof(bool), typeof(ListViewEx), new PropertyMetadata(false));

        public static readonly DependencyProperty IsSortableProperty =
            DependencyProperty.Register("IsSortable", typeof(Boolean), typeof(ListViewEx), new PropertyMetadata(false, OnRegisterSortableGrid));

        protected override void OnItemsSourceChanged(System.Collections.IEnumerable oldValue, System.Collections.IEnumerable newValue)
        {
            base.OnItemsSourceChanged(oldValue, newValue);

            if (AutoGenerateColumns)
            {
                GridView gridView = new GridView();

                Type sourceItemType = ItemsSource.AsQueryable().ElementType;
                PropertyInfo[] properties = sourceItemType.GetProperties();

                foreach (var prop in properties)
                {
                    GridViewColumn column = new GridViewColumn();

                    if (prop.PropertyType == typeof(BitmapImage))
                    {
                        DataTemplate template = new DataTemplate();

                        FrameworkElementFactory childFactory = new FrameworkElementFactory(typeof(System.Windows.Controls.Image));

                        childFactory.SetBinding(System.Windows.Controls.Image.SourceProperty, new Binding(prop.Name));
                        childFactory.SetValue(WidthProperty, 16.0);
                        template.VisualTree = childFactory;

                        column.CellTemplate = template;
                    }
                    else
                    {
                        column.Header = (prop.GetCustomAttributes(typeof(DescriptionAttribute), false).First() as DescriptionAttribute).Description;
                        column.DisplayMemberBinding = new Binding(prop.Name);
                        column.Width = double.NaN;
                    }

                    gridView.Columns.Add(column);
                }

                View = gridView;
            }
        }


        private static GridViewColumnHeader _lastHeaderClicked;
        private static ListSortDirection _lastDirection;
        private static ListView _listView;

        private static void OnRegisterSortableGrid(DependencyObject obj, DependencyPropertyChangedEventArgs args)
        {
            ListView grid = obj as ListView;

            if (grid != null)
            {
                _listView = obj as ListView;
                grid.AddHandler(ButtonBase.ClickEvent, new RoutedEventHandler(GridViewColumnHeaderClickedHandler));
            }
        }

        private static void GridViewColumnHeaderClickedHandler(object sender, RoutedEventArgs e)
        {
            GridViewColumnHeader headerClicked = e.OriginalSource as GridViewColumnHeader;

            if (headerClicked != null)
            {
                ListSortDirection direction;

                if (headerClicked != _lastHeaderClicked)
                {
                    direction = ListSortDirection.Ascending;
                }
                else
                {
                    direction = _lastDirection == ListSortDirection.Ascending ? ListSortDirection.Descending : ListSortDirection.Ascending;
                }

                if (headerClicked.Column.DisplayMemberBinding != null)
                {
                    Sort((headerClicked.Column.DisplayMemberBinding as Binding).Path.Path, direction);

                    _lastHeaderClicked = headerClicked;
                    _lastDirection = direction;
                }
            }
        }

        private static void Sort(string propertyName, ListSortDirection direction)
        {
            var view = (ListCollectionView)CollectionViewSource.GetDefaultView(_listView.ItemsSource);

            if (view != null)
            {
                try
                {
                    view.CustomSort = new ListViewComparer { PropertyName = propertyName, SortDirection = direction };
                    _listView.Items.Refresh();
                }
                catch (Exception)
                {
                }
            }
        }
    }


 public class ListViewComparer : IComparer
    {
        public string PropertyName { get; set; }

        public ListSortDirection SortDirection { get; set; }

        public int Compare(object x, object y)
        {
            try
            {
                int result = 0;

                var pro1 = x.GetType().GetProperty(PropertyName);
                var pro2 = y.GetType().GetProperty(PropertyName);

                var valx = pro1.GetValue(x, null);
                var valy = pro2.GetValue(y, null);

                if (valx == null && valy == null) return 0;
                if (valx == null) return -1;
                if (valy == null) return 1;

                var type = pro1.PropertyType;

                if (type.IsGenericType && (type.GetGenericTypeDefinition() == typeof(Nullable<>)))
                {
                    type = Nullable.GetUnderlyingType(type);
                }

                switch (Type.GetTypeCode(type))
                {
                    case TypeCode.String:
                    case TypeCode.Boolean:
                        result = valx.ToString().CompareTo(valy.ToString());
                        break;
                    case TypeCode.Single:
                    case TypeCode.Double:
                    case TypeCode.Decimal:
                        result = Convert.ToDouble(valx).CompareTo(Convert.ToDouble(valy));
                        break;
                    case TypeCode.Byte:
                    case TypeCode.SByte:
                    case TypeCode.Int16:
                    case TypeCode.Int32:
                    case TypeCode.Int64:
                        result = Convert.ToInt64(valx).CompareTo(Convert.ToInt64(valy));
                        break;
                    case TypeCode.UInt16:
                    case TypeCode.UInt32:
                    case TypeCode.UInt64:
                        result = Convert.ToUInt64(valx).CompareTo(Convert.ToUInt64(valy));
                        break;
                    case TypeCode.DateTime:
                        result = Convert.ToDateTime(valx).CompareTo(Convert.ToDateTime(valy));
                        break;
                }

                if (SortDirection == ListSortDirection.Descending) result *= -1;

                return result;
            }
            catch (Exception)
            {
                return 0;
            }
        }
    }



четверг, 24 мая 2012 г.

Set docx header using ooxml sdk C#


 foreach (var headerPart in mainDocumentPart.HeaderParts)
                {
                    foreach (var text in headerPart.Header.Descendants<Text>())
                    {
                        if (text.Text.Contains("approveNumber"))
                        {

                            text.Text = "newHeader";
                            headerPart.Header.Save();
                            break;
                        }
                    }
                }

Англо-русский словарь заимствованных слов (English-Russian loanwords dictionary)



1. Compose - составлять (композиция)
2. Assistance - помощь, содействие (асистент)
3. Meet - встречаться (митинг)
4. Repeat - повторять (репетиция)
5. Plenty -изобилие, множество (плантация)
6. Opposit - напротив (оппозиция)
7. Merchant - торговец (мерчандайзинг)
8. Fancy - фантастический, причудливый (фантастика)
9. Temper - характер (темперамент)
10. Patient - терпеливый, страдающий (пациент)
11. Vine - виноградная лоза (вино)
12. Grace - изящество (грация)
13. Insult - оскорбление, обида, кровоизлияние (инсульт)
14. Rosy - розовый, румяный, цветущий (роза)
15. Fury - неистовство, ярость (Фурия - богиня мести)
16. Spindle - веретено (шпиндель)
17. Accident - авария, катастрофа, проишествие (инцидент)
18. Cheat - мошенник (читер)
19. Rent - сдавать в аренду (рента)
20. Breif - короткий (брифинг)
21. Purge - очищать, освобождать (Пурген)
22. Grab - хватать (грабитель)
23. Attract - привлекать (аттракцион)
24. Barrel - бочка (баррель нефти)
25. Folk - народ, народный (фольклор)
26. Kick - удар, толчок (лоу кик, кикбоксёр )
27. Stick -приклеивать, наклеивать (стикер)
28. Bandage - бинт (бандаж)
29. Rerely - редко (раритетный)
30. Pinch - ущипнуть (пинцет)
31. Loyal -  верный (лояльный)
32. Argue - спорить, убеждать (аргумент)
33. Deal -  сделка (диллер)
34. Sole - единственный (соло)
35. Substitute - заменять (товар- субститут)
36. Investigate - исследовать (инвестиции)
37. Memory - память (мемуары)
38.Cannon - пушка (канонада)
39. Pill -таблетка (пилюля)
40. Ruin - разрушать (руины)
41. Infant - младенец (инфантильный)
42. Dive - нырять (дайвинг)
43. Discont - скидка (дисконтная карта)
44. Heel - пятка (Ахилес)
45. Feminine - женский (феминистки)
46. Provide - обеспечивать (интернет-провайдер)
47. Produce - выпускать (музыкальный продюсер)
48.Penalty - штраф (пенальти в футболе)
49. Promote - продвигать (промоутеры товаров)
50. Violin - скрипка (виолончель)
51.Van - фургон (минивэн)
52. Leg - нога (леггенсы)

среда, 23 мая 2012 г.

Split (merge) table cell docx using ooxml sdk C# with the same text

var tables = mainDocumentPart.Document.Body.Elements<Table>().ToList();


var rows = tables[1].Elements<TableRow>().ToArray();

            var wasRestart = false;

            for (int i = 0; i < rows.Length - 1; i++)
            {
                if (rows[i].Elements<TableCell>().ElementAt(1).Elements<Paragraph>().First().Elements<Run>().First().Elements<Text>().First().Text ==
                   rows[i + 1].Elements<TableCell>().ElementAt(1).Elements<Paragraph>().First().Elements<Run>().First().Elements<Text>().First().Text)
                {
                    rows[i].Elements<TableCell>().ElementAt(1).TableCellProperties.VerticalMerge = new VerticalMerge() { Val = wasRestart ? MergedCellValues.Continue : MergedCellValues.Restart };
                    rows[i + 1].Elements<TableCell>().ElementAt(1).TableCellProperties.VerticalMerge = new VerticalMerge();

                    rows[i].Elements<TableCell>().ElementAt(4).TableCellProperties.VerticalMerge = new VerticalMerge() { Val = wasRestart ? MergedCellValues.Continue : MergedCellValues.Restart };
                    rows[i + 1].Elements<TableCell>().ElementAt(4).TableCellProperties.VerticalMerge = new VerticalMerge();

                    wasRestart = true;
                }
                else
                {
                    wasRestart = false;
                }
            }

суббота, 12 мая 2012 г.

Merge docx files using C# OOXML SDK WordprocessingDocument class

This code create one docx document from template replacing certain fields in template.


 class DocumentInfo
    {
        public string ProductName { get; set; }

        public string AWPCount { get; set; }

        public string RegNumber { get; set; }

        public string OrganizationName { get; set; }

        public string LifeTime { get; set; }
    }


public static byte[] GetDocx(string templatePath, DocumentInfo[] documentInfos)
        {
            if (documentInfos.Length == 0)
            {
                throw new Exception("documentInfos count = 0!");
            }

            if (!File.Exists(templatePath))
            {
                throw new FileNotFoundException("Document template not found", templatePath);
            }

            var template = File.ReadAllBytes(templatePath);

            var mainStream = new MemoryStream();

            mainStream.Write(template, 0, template.Length);
            mainStream.Position = 0;

            byte[] result;
            try
            {
                using (var mainDocument = WordprocessingDocument.Open(mainStream, true))
                {
                    var mainXml = mainDocument.MainDocumentPart.Document.Body.OuterXml;

                    mainXml = mainXml.Replace("productName", documentInfos[0].ProductName);
                    mainXml = mainXml.Replace("AWPCount", documentInfos[0].AWPCount);
                    mainXml = mainXml.Replace("regNumber", documentInfos[0].RegNumber);
                    mainXml = mainXml.Replace("organizationName", documentInfos[0].OrganizationName);
                    mainXml = mainXml.Replace("lifeTime", documentInfos[0].LifeTime);

                    var mainBody = XElement.Parse(mainXml);

                    for (var i = 1; i < documentInfos.Length; i++)
                    {
                        using (var tempDocument = WordprocessingDocument.Open(new MemoryStream(template), false))
                        {
                            var tempXml = tempDocument.MainDocumentPart.Document.Body.OuterXml;

                            tempXml = tempXml.Replace("productName", documentInfos[i].ProductName);
                            tempXml = tempXml.Replace("AWPCount", documentInfos[i].AWPCount);
                            tempXml = tempXml.Replace("regNumber", documentInfos[i].RegNumber);
                            tempXml = tempXml.Replace("organizationName", documentInfos[i].OrganizationName);
                            tempXml = tempXml.Replace("lifeTime", documentInfos[i].LifeTime);

                            var tempBody = XElement.Parse(tempXml);

                            mainBody.Add(tempBody);
                            mainDocument.MainDocumentPart.Document.Body = new Body(mainBody.ToString());
                            mainDocument.MainDocumentPart.Document.Save();
                            mainDocument.Package.Flush();
                        }
                    }
                }
            }
            catch (Exception e)
            {
                throw new Exception(string.Format(CultureInfo.CurrentCulture, "Error while merging files.{0", 1), e);
            }
            finally
            {
                result = mainStream.ToArray();
                mainStream.Close();
                mainStream.Dispose();
            }

            return result;
        }

вторник, 24 апреля 2012 г.

Get share folder effective rights using C#


 class NetDirectorySecurity : NativeObjectSecurity
    {
        public NetDirectorySecurity(string ResName, AccessControlSections IncludeSections)
            : base(true, ResourceType.LMShare, ResName, IncludeSections)
        {
        }

        private static FileSystemRights RightsFromAccessMask(int accessMask)
        {
            return (FileSystemRights)accessMask;
        }

        public sealed override AccessRule AccessRuleFactory(IdentityReference identityReference, int accessMask,
            bool isInherited, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, AccessControlType type)
        {
            return new FileSystemAccessRule(identityReference, RightsFromAccessMask(accessMask), inheritanceFlags, propagationFlags, type);
        }

        public sealed override AuditRule AuditRuleFactory(IdentityReference identityReference, int accessMask,
            bool isInherited, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, AuditFlags flags)
        {
            return new FileSystemAuditRule(identityReference, RightsFromAccessMask(accessMask), inheritanceFlags, propagationFlags, flags);
        }

        public override Type AccessRightType { get { return typeof(FileSystemRights); } }
        public override Type AccessRuleType { get { return typeof(FileSystemAccessRule); } }
        public override Type AuditRuleType { get { return typeof(FileSystemAuditRule); } }
    } 


                        NetDirectorySecurity nds = new NetDirectorySecurity(sharedName, AccessControlSections.Access);
                     
                        var permissions = nds.GetAccessRules(true, true, typeof(SecurityIdentifier));
                        FileSystemRights denyRights = 0;
                        FileSystemRights allowRights = 0;

                        var accessRules = permissions.Cast<FileSystemAccessRule>().Where(ar => ar.IdentityReference.Value == sid).ToList();

                        if (accessRules.Count == 0) mask = 0;

                        foreach (var accessRule in accessRules)
                        {
                            if (accessRule.AccessControlType == AccessControlType.Deny)
                            {
                                denyRights |= accessRule.FileSystemRights;
                            }
                            else
                            {
                                allowRights |= accessRule.FileSystemRights;
                            }
                        }

                        var mask = (int)((allowRights | denyRights) ^ denyRights);
                       

Get share folder audit permissions using .net C#


    class NetDirectorySecurity : NativeObjectSecurity
    {
        public NetDirectorySecurity(string ResName, AccessControlSections IncludeSections)
            : base(true, ResourceType.LMShare, ResName, IncludeSections)
        {
        }

        private static FileSystemRights RightsFromAccessMask(int accessMask)
        {
            return (FileSystemRights)accessMask;
        }

        public sealed override AccessRule AccessRuleFactory(IdentityReference identityReference, int accessMask,
            bool isInherited, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, AccessControlType type)
        {
            return new FileSystemAccessRule(identityReference, RightsFromAccessMask(accessMask), inheritanceFlags, propagationFlags, type);
        }

        public sealed override AuditRule AuditRuleFactory(IdentityReference identityReference, int accessMask,
            bool isInherited, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, AuditFlags flags)
        {
            return new FileSystemAuditRule(identityReference, RightsFromAccessMask(accessMask), inheritanceFlags, propagationFlags, flags);
        }

        public override Type AccessRightType { get { return typeof(FileSystemRights); } }
        public override Type AccessRuleType { get { return typeof(FileSystemAccessRule); } }
        public override Type AuditRuleType { get { return typeof(FileSystemAuditRule); } }
    }



NetDirectorySecurity nds = new NetDirectorySecurity(sharedName, AccessControlSections.Audit);

                        var permissions = nds.GetAuditRules(true, true, typeof(SecurityIdentifier));
                        FileSystemRights failRights = 0;
                        FileSystemRights successRights = 0;
                        FileSystemRights noneRights = 0;

                        var auditRules = permissions.Cast<FileSystemAuditRule>().Where(ar => ar.IdentityReference.Value == sid).ToList();

                        if (auditRules.Count == 0)
                        {
                            successfullAuditMask = 0;
                            failedAuditMask = 0;
                        }

                        var auditFlagsValues = Enum.GetValues(typeof(AuditFlags));

                        foreach (var auditRule in auditRules)
                        {
                            var closureRule = auditRule;

                            foreach (AuditFlags value in auditFlagsValues.Cast<AuditFlags>().Where(value => (closureRule.AuditFlags & value) == value))
                            {
                                switch (value)
                                {
                                    case AuditFlags.Failure:
                                        failRights |= auditRule.FileSystemRights;
                                        break;
                                    case AuditFlags.Success:
                                        successRights |= auditRule.FileSystemRights;
                                        break;
                                    case AuditFlags.None:
                                        noneRights |= auditRule.FileSystemRights;
                                        break;
                                }
                            }
                        }

                        successfullAuditMask = (int)successRights;
                        failedAuditMask = (int)failRights;

Set DACL field of shared folder security descriptor using wmi C#


 var searcher = new ManagementObjectSearcher("\\\\.\\ROOT\\CIMV2", "SELECT * FROM Win32_LogicalShareSecuritySetting WHERE Name = \"Share\"");

                        var queryResult = searcher.Get();

                        foreach (ManagementObject findedItem in queryResult)
                        {
                            var caption = findedItem["Caption"];

                            InvokeMethodOptions options = new InvokeMethodOptions();

                            ManagementBaseObject outParamsMthd = findedItem.InvokeMethod("GetSecurityDescriptor", null, options);

                            ManagementBaseObject descriptor = outParamsMthd["Descriptor"] as ManagementBaseObject;

                            ManagementObject newAce = new ManagementClass(new ManagementScope("\\\\.\\ROOT\\CIMV2"), new ManagementPath("Win32_ACE"), null);

                            ManagementObject trustee = new ManagementClass(new ManagementScope("\\\\.\\ROOT\\CIMV2"), new ManagementPath("Win32_Trustee"), null);

                            trustee.Properties["SIDString"].Value = "S-1-5-32-544"; //Administrators

                            newAce.Properties["Trustee"].Value = trustee;

                            newAce.Properties["AccessMask"].Value = 262144; //delete

                            // Allow access to resource.
                            newAce.Properties["AceType"].Value = 0;

                            // ACL will be inherited.
                            newAce.Properties["AceFlags"].Value = 16;

                            // Add ACE to DACL and set to descriptor.
                            ArrayList daclArray = new ArrayList() { newAce };

                            descriptor.Properties["DACL"].Value = daclArray.ToArray();

                            ManagementBaseObject inParams = findedItem.GetMethodParameters("SetSecurityDescriptor");

                            inParams["Descriptor"] = descriptor;

                            var res = findedItem.InvokeMethod("SetSecurityDescriptor", inParams, null);

                            Int32 ReturnValue = Convert.ToInt32(res.Properties["ReturnValue"].Value);
                        }

Get DACL field of shared folder security descriptor using wmi C#


 var searcher = new ManagementObjectSearcher("\\\\.\\ROOT\\CIMV2", "SELECT * FROM Win32_LogicalShareSecuritySetting WHERE Name = \"Share\"");

                        var queryResult = searcher.Get();

                        foreach (ManagementObject findedItem in queryResult)
                        {
                            var caption = findedItem["Caption"];

                            InvokeMethodOptions options = new InvokeMethodOptions();

                            ManagementBaseObject outParamsMthd = findedItem.InvokeMethod("GetSecurityDescriptor", null, options);

                            ManagementBaseObject descriptor = outParamsMthd["Descriptor"] as ManagementBaseObject;

                            ManagementBaseObject[] dacl = descriptor["DACL"] as ManagementBaseObject[];

                            foreach (var baseObject in dacl)
                            {
                                var type = baseObject.Properties["AceType"].Value;
                                var mask = baseObject.Properties["AccessMask"].Value;
                                var flags = baseObject.Properties["AceFlags"].Value;
                            }

воскресенье, 19 февраля 2012 г.

Get another process command line, image path, parent PID, current directory C#


 private int GetParentProcessID(IntPtr handle)
        {
            NativeMethods.ProcessBasicInformation pbi = new NativeMethods.ProcessBasicInformation();
            int returnLength;
            int status = NativeMethods.NtQueryInformationProcess(handle, 0, out pbi, Marshal.SizeOf(pbi), out returnLength);

            if (status != 0) throw new Win32Exception(status);

            var result = pbi.InheritedFromUniqueProcessId.ToInt32();

            return result;
        }

        private string GetProcessCommandLine(IntPtr handle)
        {
            NativeMethods.ProcessBasicInformation pbi;

            int returnLength;
            int status = NativeMethods.NtQueryInformationProcess(handle, 0, out pbi, Marshal.SizeOf(typeof(NativeMethods.ProcessBasicInformation)), out returnLength);

            if (status != 0) throw new Win32Exception(status);

            var result = GetPebString(PebOffset.CommandLine, pbi.PebBaseAddress, handle);

            return result;
        }

        private string GetProcessImagePath(IntPtr handle)
        {
            NativeMethods.ProcessBasicInformation pbi;

            int returnLength;
            int status = NativeMethods.NtQueryInformationProcess(handle, 0, out pbi, Marshal.SizeOf(typeof(NativeMethods.ProcessBasicInformation)), out returnLength);

            if (status != 0) throw new Win32Exception(status);

            var result = GetPebString(PebOffset.ImagePathName, pbi.PebBaseAddress, handle);

            return result;
        }

        private IntPtr IncrimentPtr(IntPtr ptr, int value)
        {
            return IntPtr.Size == sizeof(Int32) ? new IntPtr(ptr.ToInt32() + value) : new IntPtr(ptr.ToInt64() + value);
        }

        private unsafe string GetPebString(PebOffset offset, IntPtr pebBaseAddress, IntPtr handle)
        {
            byte* buffer = stackalloc byte[IntPtr.Size];

            ReadMemory(IncrimentPtr(pebBaseAddress, NativeMethods.Peb.ProcessParametersOffset), buffer, IntPtr.Size, handle);

            IntPtr processParameters = *(IntPtr*)buffer;

            int realOffset = GetPebOffset(offset);

            NativeMethods.UnicodeString pebStr;

            ReadMemory(IncrimentPtr(processParameters, realOffset), &pebStr, Marshal.SizeOf(typeof(NativeMethods.UnicodeString)), handle);

            var str = Encoding.Unicode.GetString(ReadMemory(pebStr.Buffer, pebStr.Length, handle), 0, pebStr.Length);

            return str;
        }

        private int GetPebOffset(PebOffset offset)
        {
            switch (offset)
            {
                case PebOffset.CommandLine:
                    return NativeMethods.RtlUserProcessParameters.CommandLineOffset;
                case PebOffset.CurrentDirectoryPath:
                    return NativeMethods.RtlUserProcessParameters.CurrentDirectoryOffset;
                case PebOffset.DesktopName:
                    return NativeMethods.RtlUserProcessParameters.DesktopInfoOffset;
                case PebOffset.DllPath:
                    return NativeMethods.RtlUserProcessParameters.DllPathOffset;
                case PebOffset.ImagePathName:
                    return NativeMethods.RtlUserProcessParameters.ImagePathNameOffset;
                case PebOffset.RuntimeData:
                    return NativeMethods.RtlUserProcessParameters.RuntimeDataOffset;
                case PebOffset.ShellInfo:
                    return NativeMethods.RtlUserProcessParameters.ShellInfoOffset;
                case PebOffset.WindowTitle:
                    return NativeMethods.RtlUserProcessParameters.WindowTitleOffset;
                default:
                    throw new ArgumentException("offset");
            }
        }

        private byte[] ReadMemory(IntPtr baseAddress, int length, IntPtr handle)
        {
            byte[] buffer = new byte[length];

            ReadMemory(baseAddress, buffer, length, handle);

            return buffer;
        }

        private unsafe int ReadMemory(IntPtr baseAddress, byte[] buffer, int length, IntPtr handle)
        {
            fixed (byte* bufferPtr = buffer) return ReadMemory(baseAddress, bufferPtr, length, handle);
        }

        private unsafe int ReadMemory(IntPtr baseAddress, void* buffer, int length, IntPtr handle)
        {
            return ReadMemory(baseAddress, new IntPtr(buffer), length, handle);
        }

        private int ReadMemory(IntPtr baseAddress, IntPtr buffer, int length, IntPtr handle)
        {
            int status;
            IntPtr retLengthIntPtr;

            if ((status = NativeMethods.NtReadVirtualMemory(handle, baseAddress, buffer, new IntPtr(length), out retLengthIntPtr)) > 0) throw new Win32Exception(status);

            return retLengthIntPtr.ToInt32();
        }


         [DllImport("ntdll.dll")]
        internal static extern int NtQueryInformationProcess(
            [In] IntPtr ProcessHandle,
            [In] int ProcessInformationClass,
            [Out] out ProcessBasicInformation ProcessInformation,
            [In] int ProcessInformationLength,
            [Out] [Optional] out int ReturnLength
            );

                [DllImport("ntdll.dll")]
        public static extern int NtReadVirtualMemory(
            [In] IntPtr processHandle,
            [In] [Optional] IntPtr baseAddress,
            [In] IntPtr buffer,
            [In] IntPtr bufferSize,
            [Out] [Optional] out IntPtr returnLength
            );




        [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)]
        public struct UnicodeString
        {
            public ushort Length;
            public ushort MaximumLength;
            public IntPtr Buffer;
        }

        [StructLayout(LayoutKind.Sequential)]
        public struct ListEntry
        {
            public IntPtr Flink;
            public IntPtr Blink;
        }

        [StructLayout(LayoutKind.Sequential)]
        public unsafe struct Peb
        {
            public static readonly int ImageSubsystemOffset =
                Marshal.OffsetOf(typeof(Peb), "ImageSubsystem").ToInt32();
            public static readonly int LdrOffset =
                Marshal.OffsetOf(typeof(Peb), "Ldr").ToInt32();
            public static readonly int ProcessHeapOffset =
                Marshal.OffsetOf(typeof(Peb), "ProcessHeap").ToInt32();
            public static readonly int ProcessParametersOffset =
                Marshal.OffsetOf(typeof(Peb), "ProcessParameters").ToInt32();

            [MarshalAs(UnmanagedType.I1)]
            public bool InheritedAddressSpace;
            [MarshalAs(UnmanagedType.I1)]
            public bool ReadImageFileExecOptions;
            [MarshalAs(UnmanagedType.I1)]
            public bool BeingDebugged;
            [MarshalAs(UnmanagedType.I1)]
            public bool BitField;
            public IntPtr Mutant;

            public IntPtr ImageBaseAddress;
            public IntPtr Ldr; // PebLdrData*
            public IntPtr ProcessParameters; // RtlUserProcessParameters*
            public IntPtr SubSystemData;
            public IntPtr ProcessHeap;
            public IntPtr FastPebLock;
            public IntPtr AtlThunkSListPtr;
            public IntPtr SparePrt2;
            public int EnvironmentUpdateCount;
            public IntPtr KernelCallbackTable;
            public int SystemReserved;
            public int SpareUlong;
            public IntPtr FreeList;
            public int TlsExpansionCounter;
            public IntPtr TlsBitmap;
            public unsafe fixed int TlsBitmapBits[2];
            public IntPtr ReadOnlySharedMemoryBase;
            public IntPtr ReadOnlySharedMemoryHeap;
            public IntPtr ReadOnlyStaticServerData;
            public IntPtr AnsiCodePageData;
            public IntPtr OemCodePageData;
            public IntPtr UnicodeCaseTableData;

            public int NumberOfProcessors;
            public int NtGlobalFlag;

            public long CriticalSectionTimeout;
            public IntPtr HeapSegmentReserve;
            public IntPtr HeapSegmentCommit;
            public IntPtr HeapDeCommitTotalFreeThreshold;
            public IntPtr HeapDeCommitFreeBlockThreshold;

            public int NumberOfHeaps;
            public int MaximumNumberOfHeaps;
            public IntPtr ProcessHeaps;

            public IntPtr GdiSharedHandleTable;
            public IntPtr ProcessStarterHelper;
            public int GdiDCAttributeList;
            public IntPtr LoaderLock;

            public int OSMajorVersion;
            public int OSMinorVersion;
            public short OSBuildNumber;
            public short OSCSDVersion;
            public int OSPlatformId;
            public int ImageSubsystem;
            public int ImageSubsystemMajorVersion;
            public int ImageSubsystemMinorVersion;
            public IntPtr ImageProcessAffinityMask;
            public unsafe fixed byte GdiHandleBuffer[GDI_HANDLE_BUFFER_SIZE];
            public IntPtr PostProcessInitRoutine;

            public IntPtr TlsExpansionBitmap;
            public unsafe fixed int TlsExpansionBitmapBits[32];

            public int SessionId;

            public long AppCompatFlags;
            public long AppCompatFlagsUser;
            public IntPtr pShimData;
            public IntPtr AppCompatInfo;

            public UnicodeString CSDVersion;

            public IntPtr ActivationContextData;
            public IntPtr ProcessAssemblyStorageMap;
            public IntPtr SystemDefaultActivationContextData;
            public IntPtr SystemAssemblyStorageMap;

            public IntPtr MinimumStackCommit;

            public IntPtr FlsCallback;
            public ListEntry FlsListHead;
            public IntPtr FlsBitmap;
            public unsafe fixed int FlsBitmapBits[FLS_MAXIMUM_AVAILABLE / (sizeof(int) * 8)];
            public int FlsHighIndex;
        }

        [StructLayout(LayoutKind.Sequential)]
            public struct RtlUserProcessParameters
            {
                public static readonly int CurrentDirectoryOffset =
                    Marshal.OffsetOf(typeof(RtlUserProcessParameters), "CurrentDirectory").ToInt32();
                public static readonly int DllPathOffset =
                    Marshal.OffsetOf(typeof(RtlUserProcessParameters), "DllPath").ToInt32();
                public static readonly int ImagePathNameOffset =
                    Marshal.OffsetOf(typeof(RtlUserProcessParameters), "ImagePathName").ToInt32();
                public static readonly int CommandLineOffset =
                    Marshal.OffsetOf(typeof(RtlUserProcessParameters), "CommandLine").ToInt32();
                public static readonly int EnvironmentOffset =
                    Marshal.OffsetOf(typeof(RtlUserProcessParameters), "Environment").ToInt32();
                public static readonly int WindowTitleOffset =
                    Marshal.OffsetOf(typeof(RtlUserProcessParameters), "WindowTitle").ToInt32();
                public static readonly int DesktopInfoOffset =
                    Marshal.OffsetOf(typeof(RtlUserProcessParameters), "DesktopInfo").ToInt32();
                public static readonly int ShellInfoOffset =
                    Marshal.OffsetOf(typeof(RtlUserProcessParameters), "ShellInfo").ToInt32();
                public static readonly int RuntimeDataOffset =
                    Marshal.OffsetOf(typeof(RtlUserProcessParameters), "RuntimeData").ToInt32();
                public static readonly int CurrentDirectoriesOffset =
                    Marshal.OffsetOf(typeof(RtlUserProcessParameters), "CurrentDirectories").ToInt32();

                public struct CurDir
                {
                    public NativeMethods.UnicodeString DosPath;
                    public IntPtr Handle;
                }

                public struct RtlDriveLetterCurDir
                {
                    public ushort Flags;
                    public ushort Length;
                    public uint TimeStamp;
                    public IntPtr DosPath;
                }

                public int MaximumLength;
                public int Length;

                public RtlUserProcessFlags Flags;
                public int DebugFlags;

                public IntPtr ConsoleHandle;
                public int ConsoleFlags;
                public IntPtr StandardInput;
                public IntPtr StandardOutput;
                public IntPtr StandardError;

                public CurDir CurrentDirectory;
                public NativeMethods.UnicodeString DllPath;
                public NativeMethods.UnicodeString ImagePathName;
                public NativeMethods.UnicodeString CommandLine;
                public IntPtr Environment;

                public int StartingX;
                public int StartingY;
                public int CountX;
                public int CountY;
                public int CountCharsX;
                public int CountCharsY;
                public int FillAttribute;

                public StartupFlags WindowFlags;
                public int ShowWindowFlags;
                public NativeMethods.UnicodeString WindowTitle;
                public NativeMethods.UnicodeString DesktopInfo;
                public NativeMethods.UnicodeString ShellInfo;
                public NativeMethods.UnicodeString RuntimeData;

                public RtlDriveLetterCurDir CurrentDirectories;
            }

        [StructLayout(LayoutKind.Sequential)]
        public struct ProcessBasicInformation
        {
            public int ExitStatus;
            public IntPtr PebBaseAddress;
            public IntPtr AffinityMask;
            public int BasePriority;
            public IntPtr UniqueProcessId;
            public IntPtr InheritedFromUniqueProcessId;
        }


четверг, 16 февраля 2012 г.

Get dns cache date from domain using C#


        [DllImport("dnsapi.dll",EntryPoint="DnsQuery_A")]
internal static extern UInt32 DnsQuery( [MarshalAs(UnmanagedType.LPStr)]string lpstrName, [MarshalAs(UnmanagedType.U2)]UInt16 wType, [MarshalAs(UnmanagedType.U4)]UInt32 fOptions,
            [MarshalAs(UnmanagedType.U4)]UInt32 t1, ref UInt32 prr, [MarshalAs(UnmanagedType.U4)]UInt32 t3 );

private class DnsInfo
        {
            public DnsInfo()
            {
                IPAddresses = new List<string>();
            }

            public string DomainName { get; set; }

            public uint TTL { get; set; }

            public List<string> IPAddresses { get; set; }
        }

        private UInt32 GetIP(Int32 ptr)
        {
            return ((NativeMethods.DNS_A_DATA)Marshal.PtrToStructure(new IntPtr(ptr), typeof(NativeMethods.DNS_A_DATA))).IpAddress;
        }


private DnsInfo GetDNSInfo(ref string strDomain)
        {
            var result = new DnsInfo();

            const int DNS_QUERY_CACHE_ONLY = 0x00000010;
            UInt32 ppQueryResultsSet = 0;

            if (NativeMethods.DnsQuery(strDomain, DNS_TYPE_A, DNS_QUERY_CACHE_ONLY, 0, ref ppQueryResultsSet, 0) == 0)
            {
                IntPtr ppr = new IntPtr(ppQueryResultsSet);

                NativeMethods.DNS_RECORD dnsrec = (NativeMethods.DNS_RECORD)Marshal.PtrToStructure(ppr, typeof(NativeMethods.DNS_RECORD));
                NativeMethods.NetApiBufferFree(ppr);


                result.DomainName = strDomain;
                result.TTL = dnsrec.dwTtl;

                var ip = new IPAddress(GetIP(ppr.ToInt32() + Marshal.SizeOf(dnsrec))).ToString();

                result.IPAddresses.Add(ip);

                var current = dnsrec.pNext;

                while (current != IntPtr.Zero)
                {
                    dnsrec = (NativeMethods.DNS_RECORD)Marshal.PtrToStructure(current, typeof(NativeMethods.DNS_RECORD));

                    // Skip over the header portion of the DNS_RECORD to the data portion.
                    ip = new IPAddress(GetIP(current.ToInt32() + Marshal.SizeOf(dnsrec))).ToString();

                    result.IPAddresses.Add(ip);

                    var old = current;
                    current = dnsrec.pNext;

                    NativeMethods.NetApiBufferFree(old);
                }

                return result;
            }

            return null;
        }

Get dns cache entry C#


  [DllImport("kernel32.dll", SetLastError = true)]
        static extern IntPtr LoadLibrary(String dllName);

        [DllImport("kernel32", CharSet = CharSet.Ansi, ExactSpelling = true, SetLastError = true)]
        static extern IntPtr GetProcAddress(IntPtr hModule, string procName);

        public struct DnsCacheEntry
        {
            public IntPtr pNext;

            [MarshalAs(UnmanagedType.LPWStr)]
            public string pszName;

            public ushort wType;

            public ushort wDataLength;

            public ulong dwFlags;
        }

        [UnmanagedFunctionPointer(CallingConvention.StdCall)]
        public delegate bool GetDNSCacheInvoker(out IntPtr dns);

        private List<string> DomainSearch()
        {
            const int DNS_TYPE_A = 0;

            var result = new List<string>();

            var hModule = LoadLibrary("dnsapi.dll");

            IntPtr fptr = GetProcAddress(hModule, "DnsGetCacheDataTable");

            IntPtr dnsPtr;

            GetDNSCacheInvoker drs = (GetDNSCacheInvoker)Marshal.GetDelegateForFunctionPointer(fptr, typeof(GetDNSCacheInvoker));

            if (drs(out dnsPtr))
            {
                var dns = (DnsCacheEntry)Marshal.PtrToStructure(dnsPtr, typeof(DnsCacheEntry));

                NativeMethods.NetApiBufferFree(dnsPtr);

                var current = dns.pNext;

                if (dns.wType == DNS_TYPE_A) result.Add(dns.pszName);

                while (current != IntPtr.Zero)
                {
                    dns = (DnsCacheEntry)Marshal.PtrToStructure(current, typeof(DnsCacheEntry));

                    var old = current;

                    current = dns.pNext;

                    if (dns.wType == DNS_TYPE_A) result.Add(dns.pszName);

                    NativeMethods.NetApiBufferFree(old);
                }
            }

            return result;
        }

понедельник, 6 февраля 2012 г.

Get local password policy (PasswordComplexity, ReversibleEncryption) C#


private void GetPasswordInfo()
        {
   
            var tempFile = Path.GetTempFileName();

            using (Process p = new Process
                                        {
                                            StartInfo =
                                                {
                                                    FileName = Environment.GetFolderPath(Environment.SpecialFolder.SystemX86) + Path.DirectorySeparatorChar + "secedit.exe",
                                                    Arguments = String.Format(@"/export /areas SECURITYPOLICY /cfg ""{0}"" /quiet", tempFile),
                                                    CreateNoWindow = true,
                                                    UseShellExecute = false
                                                }
                                        })
            {
                p.Start();
                p.WaitForExit();
            }

            var file = IniFile.Load(tempFile);

            //TODO Use regex to find nessesary string values
            IniSection systemAccess;
            string passwordComplexityString;
            int passwordComplexityInt;

            var passwordComplexity = file.Sections.TryGetValue("System Access", out systemAccess)
                && systemAccess.TryGetValue("PasswordComplexity", out passwordComplexityString)
                && Int32.TryParse(passwordComplexityString, out passwordComplexityInt)
                && passwordComplexityInt == 1;

            string reversibleEncryptionString;
            int reversibleEncryptionInt;

            var reversibleEncryption = file.Sections.TryGetValue("System Access", out systemAccess)
                && systemAccess.TryGetValue("ClearTextPassword", out reversibleEncryptionString)
                && Int32.TryParse(reversibleEncryptionString, out reversibleEncryptionInt)
                && reversibleEncryptionInt == 1;
        }


 private class IniFile
        {
            public static IniFile Load(string filename)
            {
                var result = new IniFile { Sections = new Dictionary<string, IniSection>() };
                var section = new IniSection(String.Empty);
                result.Sections.Add(section.Name, section);

                foreach (var line in File.ReadAllLines(filename))
                {
                    var trimedLine = line.Trim();
                    switch (line[0])
                    {
                        case ';':
                            continue;
                        case '[':
                            section = new IniSection(trimedLine.Substring(1, trimedLine.Length - 2));
                            result.Sections.Add(section.Name, section);
                            break;
                        default:
                            var parts = trimedLine.Split('=');
                            if (parts.Length > 1)
                            {
                                section.Add(parts[0].Trim(), parts[1].Trim());
                            }
                            break;
                    }
                }

                return result;
            }

            public IDictionary<string, IniSection> Sections { get; private set; }
        }

        private class IniSection : Dictionary<string, string>
        {
            public IniSection(string name)
                : base(StringComparer.OrdinalIgnoreCase)
            {
                Name = name;
            }

            public string Name { get; private set; }
        }


пятница, 3 февраля 2012 г.

Get local system users info using C#


 var path = string.Format("WinNT://{0},computer", Environment.MachineName);

            using (var computerEntry = new DirectoryEntry(path))
            {
                foreach (DirectoryEntry childEntry in computerEntry.Children)
                {
                    if (childEntry.SchemaClassName == "User")
                    {
                        using (var context = new PrincipalContext(ContextType.Machine))
                        {
                            using (var user = UserPrincipal.FindByIdentity(context, childEntry.Name))
                            {
                               //Do something here
                            }
                        }
                    }
                }
            }


Alternative code:


var ps = new PrincipalSearcher { QueryFilter = new UserPrincipal(new PrincipalContext(ContextType.Machine, Environment.MachineName)) { Name = "*" } };

            foreach (var secPrinc in ps.FindAll().OrderBy(u => u.Name))
            {
                var u = secPrinc;

                System.Windows.Application.Current.Dispatcher.Invoke(
                    (Action)
                    (() =>
                     _collection.Add(
                         new UserInfo()
                             {
                                 Name = u.Name,
                                 Description = u.Description,
                                 SID = u.Sid.ToString(),
                                 IsEnabled = (u as UserPrincipal).Enabled.ToString(),
                                 Groups = u.GetGroups().Aggregate(string.Empty, (all, next) => all + (all != string.Empty ? "," : string.Empty) + next.Name),
                                 LastLogon = (u as UserPrincipal).LastLogon,
                                 LastPasswordSet = (u as UserPrincipal).LastPasswordSet,
                             })));
            }