forked from cloudbase/windows-imaging-tools
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Interop.ps1
1355 lines (1146 loc) · 49.5 KB
/
Interop.ps1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
$code = @"
/*
From: http://gallery.technet.microsoft.com/scriptcenter/Convert-WindowsImageps1-0fe23a8f
*/
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Security;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Xml.Linq;
using System.Xml.XPath;
using Microsoft.Win32.SafeHandles;
namespace WIMInterop {
/// <summary>
/// P/Invoke methods and associated enums, flags, and structs.
/// </summary>
public class
NativeMethods {
#region VHD
public const Int32 ERROR_SUCCESS = 0;
public const int OPEN_VIRTUAL_DISK_RW_DEPTH_DEFAULT = 1;
public const int VIRTUAL_STORAGE_TYPE_DEVICE_ISO = 1;
public const int VIRTUAL_STORAGE_TYPE_DEVICE_VHD = 2;
public const int VIRTUAL_STORAGE_TYPE_DEVICE_VHDX = 3;
public const int CREATE_VIRTUAL_DISK_PARAMETERS_DEFAULT_SECTOR_SIZE = 0x200;
public static readonly Guid VIRTUAL_STORAGE_TYPE_VENDOR_MICROSOFT = new Guid("EC984AEC-A0F9-47e9-901F-71415A66345B");
public enum CREATE_VIRTUAL_DISK_FLAG : int {
CREATE_VIRTUAL_DISK_FLAG_NONE = 0x00000000,
CREATE_VIRTUAL_DISK_FLAG_FULL_PHYSICAL_ALLOCATION = 0x00000001
}
public enum CREATE_VIRTUAL_DISK_VERSION : int {
CREATE_VIRTUAL_DISK_VERSION_UNSPECIFIED = 0,
CREATE_VIRTUAL_DISK_VERSION_1 = 1
}
public enum ATTACH_VIRTUAL_DISK_FLAG : int {
ATTACH_VIRTUAL_DISK_FLAG_NONE = 0x00000000,
ATTACH_VIRTUAL_DISK_FLAG_READ_ONLY = 0x00000001,
ATTACH_VIRTUAL_DISK_FLAG_NO_DRIVE_LETTER = 0x00000002,
ATTACH_VIRTUAL_DISK_FLAG_PERMANENT_LIFETIME = 0x00000004,
ATTACH_VIRTUAL_DISK_FLAG_NO_LOCAL_HOST = 0x00000008
}
public enum ATTACH_VIRTUAL_DISK_VERSION : int {
ATTACH_VIRTUAL_DISK_VERSION_UNSPECIFIED = 0,
ATTACH_VIRTUAL_DISK_VERSION_1 = 1
}
public enum DETACH_VIRTUAL_DISK_FLAG : int {
DETACH_VIRTUAL_DISK_FLAG_NONE = 0
}
public enum OPEN_VIRTUAL_DISK_FLAG : int {
OPEN_VIRTUAL_DISK_FLAG_NONE = 0x00000000,
OPEN_VIRTUAL_DISK_FLAG_NO_PARENTS = 0x00000001,
OPEN_VIRTUAL_DISK_FLAG_BLANK_FILE = 0x00000002,
OPEN_VIRTUAL_DISK_FLAG_BOOT_DRIVE = 0x00000004
}
public enum OPEN_VIRTUAL_DISK_VERSION : int {
OPEN_VIRTUAL_DISK_VERSION_1 = 1
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct ATTACH_VIRTUAL_DISK_PARAMETERS {
public ATTACH_VIRTUAL_DISK_VERSION Version;
public ATTACH_VIRTUAL_DISK_PARAMETERS_Version1 Version1;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct ATTACH_VIRTUAL_DISK_PARAMETERS_Version1 {
public Int32 Reserved;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct OPEN_VIRTUAL_DISK_PARAMETERS {
public OPEN_VIRTUAL_DISK_VERSION Version;
public OPEN_VIRTUAL_DISK_PARAMETERS_Version1 Version1;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct OPEN_VIRTUAL_DISK_PARAMETERS_Version1 {
public Int32 RWDepth;
}
public enum VIRTUAL_DISK_ACCESS_MASK : int {
VIRTUAL_DISK_ACCESS_ATTACH_RO = 0x00010000,
VIRTUAL_DISK_ACCESS_ATTACH_RW = 0x00020000,
VIRTUAL_DISK_ACCESS_DETACH = 0x00040000,
VIRTUAL_DISK_ACCESS_GET_INFO = 0x00080000,
VIRTUAL_DISK_ACCESS_CREATE = 0x00100000,
VIRTUAL_DISK_ACCESS_METAOPS = 0x00200000,
VIRTUAL_DISK_ACCESS_READ = 0x000d0000,
VIRTUAL_DISK_ACCESS_ALL = 0x003f0000,
VIRTUAL_DISK_ACCESS_WRITABLE = 0x00320000
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct CREATE_VIRTUAL_DISK_PARAMETERS {
public CREATE_VIRTUAL_DISK_VERSION Version;
public CREATE_VIRTUAL_DISK_PARAMETERS_Version1 Version1;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct CREATE_VIRTUAL_DISK_PARAMETERS_Version1 {
public Guid UniqueId;
public Int64 MaximumSize;
public Int32 BlockSizeInBytes;
public Int32 SectorSizeInBytes;
public IntPtr ParentPath;
public IntPtr SourcePath;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct VIRTUAL_STORAGE_TYPE {
public Int32 DeviceId;
public Guid VendorId;
}
[DllImport("virtdisk.dll", CharSet = CharSet.Unicode)]
public static extern Int32 AttachVirtualDisk(IntPtr VirtualDiskHandle, IntPtr SecurityDescriptor, ATTACH_VIRTUAL_DISK_FLAG Flags, Int32 ProviderSpecificFlags, ref ATTACH_VIRTUAL_DISK_PARAMETERS Parameters, IntPtr Overlapped);
[DllImport("virtdisk.dll", CharSet = CharSet.Unicode)]
public static extern Int32 DetachVirtualDisk(IntPtr VirtualDiskHandle, DETACH_VIRTUAL_DISK_FLAG Flags, Int32 ProviderSpecificFlags);
[DllImportAttribute("kernel32.dll", SetLastError = true)]
[return: MarshalAsAttribute(UnmanagedType.Bool)]
public static extern Boolean CloseHandle(IntPtr hObject);
[DllImport("virtdisk.dll", CharSet = CharSet.Unicode)]
public static extern Int32 OpenVirtualDisk(ref VIRTUAL_STORAGE_TYPE VirtualStorageType, String Path, VIRTUAL_DISK_ACCESS_MASK VirtualDiskAccessMask, OPEN_VIRTUAL_DISK_FLAG Flags, ref OPEN_VIRTUAL_DISK_PARAMETERS Parameters, ref IntPtr Handle);
[DllImport("virtdisk.dll", CharSet = CharSet.Unicode)]
public static extern Int32 GetVirtualDiskPhysicalPath(IntPtr VirtualDiskHandle,
ref UInt64 DiskPathSizeInBytes, [Out] StringBuilder DiskPath);
[DllImport("virtdisk.dll", CharSet = CharSet.Unicode)]
public static extern Int32 CreateVirtualDisk(ref VIRTUAL_STORAGE_TYPE VirtualStorageType, String Path, VIRTUAL_DISK_ACCESS_MASK VirtualDiskAccessMask, IntPtr SecurityDescriptor, CREATE_VIRTUAL_DISK_FLAG Flags, int ProviderSpecificFlags, ref CREATE_VIRTUAL_DISK_PARAMETERS Parameters, IntPtr Overlapped, ref IntPtr Handle);
#endregion VHD
#region Delegates and Callbacks
#region WIMGAPI
///<summary>
///User-defined function used with the RegisterMessageCallback or UnregisterMessageCallback function.
///</summary>
///<param name="MessageId">Specifies the message being sent.</param>
///<param name="wParam">Specifies additional message information. The contents of this parameter depend on the value of the
///MessageId parameter.</param>
///<param name="lParam">Specifies additional message information. The contents of this parameter depend on the value of the
///MessageId parameter.</param>
///<param name="UserData">Specifies the user-defined value passed to RegisterCallback.</param>
///<returns>
///To indicate success and to enable other subscribers to process the message return WIM_MSG_SUCCESS.
///To prevent other subscribers from receiving the message, return WIM_MSG_DONE.
///To cancel an image apply or capture, return WIM_MSG_ABORT_IMAGE when handling the WIM_MSG_PROCESS message.
///</returns>
public delegate uint
WimMessageCallback(
uint MessageId,
IntPtr wParam,
IntPtr lParam,
IntPtr UserData
);
public static void
RegisterMessageCallback(
WimFileHandle hWim,
WimMessageCallback callback) {
uint _callback = NativeMethods.WimRegisterMessageCallback(hWim, callback, IntPtr.Zero);
int rc = Marshal.GetLastWin32Error();
if (0 != rc) {
// Throw an exception if something bad happened on the Win32 end.
throw
new InvalidOperationException(
string.Format(
CultureInfo.CurrentCulture,
"Unable to register message callback."
));
}
}
public static void
UnregisterMessageCallback(
WimFileHandle hWim,
WimMessageCallback registeredCallback) {
bool status = NativeMethods.WimUnregisterMessageCallback(hWim, registeredCallback);
int rc = Marshal.GetLastWin32Error();
if (!status) {
throw
new InvalidOperationException(
string.Format(
CultureInfo.CurrentCulture,
"Unable to unregister message callback."
));
}
}
#endregion WIMGAPI
#endregion Delegates and Callbacks
#region Constants
#region WIMGAPI
public const uint WIM_FLAG_VERIFY = 0x00000002;
public const uint WIM_FLAG_INDEX = 0x00000004;
public const uint WM_APP = 0x00008000;
#endregion WIMGAPI
#endregion Constants
#region WIMGAPI
[FlagsAttribute]
internal enum
WimCreateFileDesiredAccess
: uint {
WimQuery = 0x00000000,
WimGenericRead = 0x80000000
}
/// <summary>
/// Specifies how the file is to be treated and what features are to be used.
/// </summary>
[FlagsAttribute]
internal enum
WimApplyFlags
: uint {
/// <summary>
/// No flags.
/// </summary>
WimApplyFlagsNone = 0x00000000,
/// <summary>
/// Reserved.
/// </summary>
WimApplyFlagsReserved = 0x00000001,
/// <summary>
/// Verifies that files match original data.
/// </summary>
WimApplyFlagsVerify = 0x00000002,
/// <summary>
/// Specifies that the image is to be sequentially read for caching or performance purposes.
/// </summary>
WimApplyFlagsIndex = 0x00000004,
/// <summary>
/// Applies the image without physically creating directories or files. Useful for obtaining a list of files and directories in the image.
/// </summary>
WimApplyFlagsNoApply = 0x00000008,
/// <summary>
/// Disables restoring security information for directories.
/// </summary>
WimApplyFlagsNoDirAcl = 0x00000010,
/// <summary>
/// Disables restoring security information for files
/// </summary>
WimApplyFlagsNoFileAcl = 0x00000020,
/// <summary>
/// The .wim file is opened in a mode that enables simultaneous reading and writing.
/// </summary>
WimApplyFlagsShareWrite = 0x00000040,
/// <summary>
/// Sends a WIM_MSG_FILEINFO message during the apply operation.
/// </summary>
WimApplyFlagsFileInfo = 0x00000080,
/// <summary>
/// Disables automatic path fixups for junctions and symbolic links.
/// </summary>
WimApplyFlagsNoRpFix = 0x00000100,
/// <summary>
/// Returns a handle that cannot commit changes, regardless of the access level requested at mount time.
/// </summary>
WimApplyFlagsMountReadOnly = 0x00000200,
/// <summary>
/// Reserved.
/// </summary>
WimApplyFlagsMountFast = 0x00000400,
/// <summary>
/// Reserved.
/// </summary>
WimApplyFlagsMountLegacy = 0x00000800
}
public enum WimMessage : uint {
WIM_MSG = WM_APP + 0x1476,
WIM_MSG_TEXT,
///<summary>
///Indicates an update in the progress of an image application.
///</summary>
WIM_MSG_PROGRESS,
///<summary>
///Enables the caller to prevent a file or a directory from being captured or applied.
///</summary>
WIM_MSG_PROCESS,
///<summary>
///Indicates that volume information is being gathered during an image capture.
///</summary>
WIM_MSG_SCANNING,
///<summary>
///Indicates the number of files that will be captured or applied.
///</summary>
WIM_MSG_SETRANGE,
///<summary>
///Indicates the number of files that have been captured or applied.
///</summary>
WIM_MSG_SETPOS,
///<summary>
///Indicates that a file has been either captured or applied.
///</summary>
WIM_MSG_STEPIT,
///<summary>
///Enables the caller to prevent a file resource from being compressed during a capture.
///</summary>
WIM_MSG_COMPRESS,
///<summary>
///Alerts the caller that an error has occurred while capturing or applying an image.
///</summary>
WIM_MSG_ERROR,
///<summary>
///Enables the caller to align a file resource on a particular alignment boundary.
///</summary>
WIM_MSG_ALIGNMENT,
WIM_MSG_RETRY,
///<summary>
///Enables the caller to align a file resource on a particular alignment boundary.
///</summary>
WIM_MSG_SPLIT,
WIM_MSG_SUCCESS = 0x00000000,
WIM_MSG_ABORT_IMAGE = 0xFFFFFFFF
}
internal enum
WimCreationDisposition
: uint {
WimOpenExisting = 0x00000003,
}
internal enum
WimActionFlags
: uint {
WimIgnored = 0x00000000
}
internal enum
WimCompressionType
: uint {
WimIgnored = 0x00000000
}
internal enum
WimCreationResult
: uint {
WimCreatedNew = 0x00000000,
WimOpenedExisting = 0x00000001
}
#endregion WIMGAPI
#region WIMGAPI P/Invoke
#region SafeHandle wrappers for WimFileHandle and WimImageHandle
public sealed class WimFileHandle : SafeHandle {
public WimFileHandle(
string wimPath)
: base(IntPtr.Zero, true) {
if (String.IsNullOrEmpty(wimPath)) {
throw new ArgumentNullException("wimPath");
}
if (!File.Exists(Path.GetFullPath(wimPath))) {
throw new FileNotFoundException((new FileNotFoundException()).Message, wimPath);
}
NativeMethods.WimCreationResult creationResult;
this.handle = NativeMethods.WimCreateFile(
wimPath,
NativeMethods.WimCreateFileDesiredAccess.WimGenericRead,
NativeMethods.WimCreationDisposition.WimOpenExisting,
NativeMethods.WimActionFlags.WimIgnored,
NativeMethods.WimCompressionType.WimIgnored,
out creationResult
);
// Check results.
if (creationResult != NativeMethods.WimCreationResult.WimOpenedExisting) {
throw new Win32Exception();
}
if (this.handle == IntPtr.Zero) {
throw new Win32Exception();
}
// Set the temporary path.
NativeMethods.WimSetTemporaryPath(
this,
Environment.ExpandEnvironmentVariables("%TEMP%")
);
}
protected override bool ReleaseHandle() {
return NativeMethods.WimCloseHandle(this.handle);
}
public override bool IsInvalid {
get { return this.handle == IntPtr.Zero; }
}
}
public sealed class WimImageHandle : SafeHandle {
public WimImageHandle(
WimFile Container,
uint ImageIndex)
: base(IntPtr.Zero, true) {
if (null == Container) {
throw new ArgumentNullException("Container");
}
if ((Container.Handle.IsClosed) || (Container.Handle.IsInvalid)) {
throw new ArgumentNullException("The handle to the WIM file has already been closed, or is invalid.", "Container");
}
if (ImageIndex > Container.ImageCount) {
throw new ArgumentOutOfRangeException("ImageIndex", "The index does not exist in the specified WIM file.");
}
this.handle = NativeMethods.WimLoadImage(
Container.Handle.DangerousGetHandle(),
ImageIndex);
}
protected override bool ReleaseHandle() {
return NativeMethods.WimCloseHandle(this.handle);
}
public override bool IsInvalid {
get { return this.handle == IntPtr.Zero; }
}
}
#endregion SafeHandle wrappers for WimFileHandle and WimImageHandle
[DllImport("Wimgapi.dll", CharSet = CharSet.Unicode, SetLastError = true, EntryPoint = "WIMCreateFile")]
internal static extern IntPtr
WimCreateFile(
[In, MarshalAs(UnmanagedType.LPWStr)] string WimPath,
[In] WimCreateFileDesiredAccess DesiredAccess,
[In] WimCreationDisposition CreationDisposition,
[In] WimActionFlags FlagsAndAttributes,
[In] WimCompressionType CompressionType,
[Out, Optional] out WimCreationResult CreationResult
);
[DllImport("Wimgapi.dll", CharSet = CharSet.Unicode, SetLastError = true, EntryPoint = "WIMCloseHandle")]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool
WimCloseHandle(
[In] IntPtr Handle
);
[DllImport("Wimgapi.dll", CharSet = CharSet.Unicode, SetLastError = true, EntryPoint = "WIMLoadImage")]
internal static extern IntPtr
WimLoadImage(
[In] IntPtr Handle,
[In] uint ImageIndex
);
[DllImport("Wimgapi.dll", CharSet = CharSet.Unicode, SetLastError = true, EntryPoint = "WIMGetImageCount")]
internal static extern uint
WimGetImageCount(
[In] WimFileHandle Handle
);
[DllImport("Wimgapi.dll", CharSet = CharSet.Unicode, SetLastError = true, EntryPoint = "WIMApplyImage")]
internal static extern bool
WimApplyImage(
[In] WimImageHandle Handle,
[In, Optional, MarshalAs(UnmanagedType.LPWStr)] string Path,
[In] WimApplyFlags Flags
);
[DllImport("Wimgapi.dll", CharSet = CharSet.Unicode, SetLastError = true, EntryPoint = "WIMGetImageInformation")]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool
WimGetImageInformation(
[In] SafeHandle Handle,
[Out] out StringBuilder ImageInfo,
[Out] out uint SizeOfImageInfo
);
[DllImport("Wimgapi.dll", CharSet = CharSet.Unicode, SetLastError = true, EntryPoint = "WIMSetTemporaryPath")]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool
WimSetTemporaryPath(
[In] WimFileHandle Handle,
[In] string TempPath
);
[DllImport("Wimgapi.dll", CharSet = CharSet.Unicode, SetLastError = true, EntryPoint = "WIMRegisterMessageCallback", CallingConvention = CallingConvention.StdCall)]
internal static extern uint
WimRegisterMessageCallback(
[In, Optional] WimFileHandle hWim,
[In] WimMessageCallback MessageProc,
[In, Optional] IntPtr ImageInfo
);
[DllImport("Wimgapi.dll", CharSet = CharSet.Unicode, SetLastError = true, EntryPoint = "WIMUnregisterMessageCallback", CallingConvention = CallingConvention.StdCall)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool
WimUnregisterMessageCallback(
[In, Optional] WimFileHandle hWim,
[In] WimMessageCallback MessageProc
);
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
internal static extern uint GetLogicalDriveStrings(uint bufferLength, [Out] char[] buffer);
#endregion WIMGAPI P/Invoke
}
#region WIM Interop
public class WimFile {
internal XDocument m_xmlInfo;
internal List<WimImage> m_imageList;
private static NativeMethods.WimMessageCallback wimMessageCallback;
#region Events
/// <summary>
/// DefaultImageEvent handler
/// </summary>
public delegate void DefaultImageEventHandler(object sender, DefaultImageEventArgs e);
///<summary>
///ProcessFileEvent handler
///</summary>
public delegate void ProcessFileEventHandler(object sender, ProcessFileEventArgs e);
///<summary>
///Enable the caller to prevent a file resource from being compressed during a capture.
///</summary>
public event ProcessFileEventHandler ProcessFileEvent;
///<summary>
///Indicate an update in the progress of an image application.
///</summary>
public event DefaultImageEventHandler ProgressEvent;
///<summary>
///Alert the caller that an error has occurred while capturing or applying an image.
///</summary>
public event DefaultImageEventHandler ErrorEvent;
///<summary>
///Indicate that a file has been either captured or applied.
///</summary>
public event DefaultImageEventHandler StepItEvent;
///<summary>
///Indicate the number of files that will be captured or applied.
///</summary>
public event DefaultImageEventHandler SetRangeEvent;
///<summary>
///Indicate the number of files that have been captured or applied.
///</summary>
public event DefaultImageEventHandler SetPosEvent;
#endregion Events
private
enum
ImageEventMessage : uint {
///<summary>
///Enables the caller to prevent a file or a directory from being captured or applied.
///</summary>
Progress = NativeMethods.WimMessage.WIM_MSG_PROGRESS,
///<summary>
///Notification sent to enable the caller to prevent a file or a directory from being captured or applied.
///To prevent a file or a directory from being captured or applied, call WindowsImageContainer.SkipFile().
///</summary>
Process = NativeMethods.WimMessage.WIM_MSG_PROCESS,
///<summary>
///Enables the caller to prevent a file resource from being compressed during a capture.
///</summary>
Compress = NativeMethods.WimMessage.WIM_MSG_COMPRESS,
///<summary>
///Alerts the caller that an error has occurred while capturing or applying an image.
///</summary>
Error = NativeMethods.WimMessage.WIM_MSG_ERROR,
///<summary>
///Enables the caller to align a file resource on a particular alignment boundary.
///</summary>
Alignment = NativeMethods.WimMessage.WIM_MSG_ALIGNMENT,
///<summary>
///Enables the caller to align a file resource on a particular alignment boundary.
///</summary>
Split = NativeMethods.WimMessage.WIM_MSG_SPLIT,
///<summary>
///Indicates that volume information is being gathered during an image capture.
///</summary>
Scanning = NativeMethods.WimMessage.WIM_MSG_SCANNING,
///<summary>
///Indicates the number of files that will be captured or applied.
///</summary>
SetRange = NativeMethods.WimMessage.WIM_MSG_SETRANGE,
///<summary>
///Indicates the number of files that have been captured or applied.
/// </summary>
SetPos = NativeMethods.WimMessage.WIM_MSG_SETPOS,
///<summary>
///Indicates that a file has been either captured or applied.
///</summary>
StepIt = NativeMethods.WimMessage.WIM_MSG_STEPIT,
///<summary>
///Success.
///</summary>
Success = NativeMethods.WimMessage.WIM_MSG_SUCCESS,
///<summary>
///Abort.
///</summary>
Abort = NativeMethods.WimMessage.WIM_MSG_ABORT_IMAGE
}
///<summary>
///Event callback to the Wimgapi events
///</summary>
private
uint
ImageEventMessagePump(
uint MessageId,
IntPtr wParam,
IntPtr lParam,
IntPtr UserData) {
uint status = (uint) NativeMethods.WimMessage.WIM_MSG_SUCCESS;
DefaultImageEventArgs eventArgs = new DefaultImageEventArgs(wParam, lParam, UserData);
switch ((ImageEventMessage)MessageId) {
case ImageEventMessage.Progress:
ProgressEvent(this, eventArgs);
break;
case ImageEventMessage.Process:
if (null != ProcessFileEvent) {
string fileToImage = Marshal.PtrToStringUni(wParam);
ProcessFileEventArgs fileToProcess = new ProcessFileEventArgs(fileToImage, lParam);
ProcessFileEvent(this, fileToProcess);
if (fileToProcess.Abort == true) {
status = (uint)ImageEventMessage.Abort;
}
}
break;
case ImageEventMessage.Error:
if (null != ErrorEvent) {
ErrorEvent(this, eventArgs);
}
break;
case ImageEventMessage.SetRange:
if (null != SetRangeEvent) {
SetRangeEvent(this, eventArgs);
}
break;
case ImageEventMessage.SetPos:
if (null != SetPosEvent) {
SetPosEvent(this, eventArgs);
}
break;
case ImageEventMessage.StepIt:
if (null != StepItEvent) {
StepItEvent(this, eventArgs);
}
break;
default:
break;
}
return status;
}
/// <summary>
/// Constructor.
/// </summary>
/// <param name="wimPath">Path to the WIM container.</param>
public
WimFile(string wimPath) {
if (string.IsNullOrEmpty(wimPath)) {
throw new ArgumentNullException("wimPath");
}
if (!File.Exists(Path.GetFullPath(wimPath))) {
throw new FileNotFoundException((new FileNotFoundException()).Message, wimPath);
}
Handle = new NativeMethods.WimFileHandle(wimPath);
// Hook up the events before we return.
//wimMessageCallback = new NativeMethods.WimMessageCallback(ImageEventMessagePump);
//NativeMethods.RegisterMessageCallback(this.Handle, wimMessageCallback);
}
/// <summary>
/// Closes the WIM file.
/// </summary>
public void
Close() {
foreach (WimImage image in Images) {
image.Close();
}
if (null != wimMessageCallback) {
NativeMethods.UnregisterMessageCallback(this.Handle, wimMessageCallback);
wimMessageCallback = null;
}
if ((!Handle.IsClosed) && (!Handle.IsInvalid)) {
Handle.Close();
}
}
/// <summary>
/// Provides a list of WimImage objects, representing the images in the WIM container file.
/// </summary>
public List<WimImage>
Images {
get {
if (null == m_imageList) {
int imageCount = (int)ImageCount;
m_imageList = new List<WimImage>(imageCount);
for (int i = 0; i < imageCount; i++) {
// Load up each image so it's ready for us.
m_imageList.Add(
new WimImage(this, (uint)i + 1));
}
}
return m_imageList;
}
}
/// <summary>
/// Provides a list of names of the images in the specified WIM container file.
/// </summary>
public List<string>
ImageNames {
get {
List<string> nameList = new List<string>();
foreach (WimImage image in Images) {
nameList.Add(image.ImageName);
}
return nameList;
}
}
/// <summary>
/// Indexer for WIM images inside the WIM container, indexed by the image number.
/// The list of Images is 0-based, but the WIM container is 1-based, so we automatically compensate for that.
/// this[1] returns the 0th image in the WIM container.
/// </summary>
/// <param name="ImageIndex">The 1-based index of the image to retrieve.</param>
/// <returns>WinImage object.</returns>
public WimImage
this[int ImageIndex] {
get { return Images[ImageIndex - 1]; }
}
/// <summary>
/// Indexer for WIM images inside the WIM container, indexed by the image name.
/// WIMs created by different processes sometimes contain different information - including the name.
/// Some images have their name stored in the Name field, some in the Flags field, and some in the EditionID field.
/// We take all of those into account in while searching the WIM.
/// </summary>
/// <param name="ImageName"></param>
/// <returns></returns>
public WimImage
this[string ImageName] {
get {
return
Images.Where(i => (
i.ImageName.ToUpper() == ImageName.ToUpper() ||
i.ImageFlags.ToUpper() == ImageName.ToUpper() ))
.DefaultIfEmpty(null)
.FirstOrDefault<WimImage>();
}
}
/// <summary>
/// Returns the number of images in the WIM container.
/// </summary>
internal uint
ImageCount {
get { return NativeMethods.WimGetImageCount(Handle); }
}
/// <summary>
/// Returns an XDocument representation of the XML metadata for the WIM container and associated images.
/// </summary>
internal XDocument
XmlInfo {
get {
if (null == m_xmlInfo) {
StringBuilder builder;
uint bytes;
if (!NativeMethods.WimGetImageInformation(Handle, out builder, out bytes)) {
throw new Win32Exception();
}
// Ensure the length of the returned bytes to avoid garbage characters at the end.
int charCount = (int)bytes / sizeof(char);
if (null != builder) {
// Get rid of the unicode file marker at the beginning of the XML.
builder.Remove(0, 1);
builder.EnsureCapacity(charCount - 1);
builder.Length = charCount - 1;
// This isn't likely to change while we have the image open, so cache it.
m_xmlInfo = XDocument.Parse(builder.ToString().Trim());
} else {
m_xmlInfo = null;
}
}
return m_xmlInfo;
}
}
public NativeMethods.WimFileHandle Handle {
get;
private set;
}
}
public class
WimImage {
internal XDocument m_xmlInfo;
public
WimImage(
WimFile Container,
uint ImageIndex) {
if (null == Container) {
throw new ArgumentNullException("Container");
}
if ((Container.Handle.IsClosed) || (Container.Handle.IsInvalid)) {
throw new ArgumentNullException("The handle to the WIM file has already been closed, or is invalid.", "Container");
}
if (ImageIndex > Container.ImageCount) {
throw new ArgumentOutOfRangeException("ImageIndex", "The index does not exist in the specified WIM file.");
}
Handle = new NativeMethods.WimImageHandle(Container, ImageIndex);
}
public enum
Architectures : uint {
x86 = 0x0,
ARM = 0x5,
IA64 = 0x6,
AMD64 = 0x9
}
public void
Close() {
if ((!Handle.IsClosed) && (!Handle.IsInvalid)) {
Handle.Close();
}
}
public void
Apply(
string ApplyToPath) {
if (string.IsNullOrEmpty(ApplyToPath)) {
throw new ArgumentNullException("ApplyToPath");
}
ApplyToPath = Path.GetFullPath(ApplyToPath);
if (!Directory.Exists(ApplyToPath)) {
throw new DirectoryNotFoundException("The WIM cannot be applied because the specified directory was not found.");
}
if (!NativeMethods.WimApplyImage(
this.Handle,
ApplyToPath,
NativeMethods.WimApplyFlags.WimApplyFlagsNone
)) {
throw new Win32Exception();
}
}
public NativeMethods.WimImageHandle
Handle {
get;
private set;
}
internal XDocument
XmlInfo {
get {
if (null == m_xmlInfo) {
StringBuilder builder;
uint bytes;
if (!NativeMethods.WimGetImageInformation(Handle, out builder, out bytes)) {
throw new Win32Exception();
}
// Ensure the length of the returned bytes to avoid garbage characters at the end.
int charCount = (int)bytes / sizeof(char);
if (null != builder) {
// Get rid of the unicode file marker at the beginning of the XML.
builder.Remove(0, 1);
builder.EnsureCapacity(charCount - 1);
builder.Length = charCount - 1;
// This isn't likely to change while we have the image open, so cache it.
m_xmlInfo = XDocument.Parse(builder.ToString().Trim());
} else {
m_xmlInfo = null;
}
}
return m_xmlInfo;
}
}
public string
ImageIndex {
get { return XmlInfo.Element("IMAGE").Attribute("INDEX").Value; }
}
public string
ImageName {
get { return XmlInfo.XPathSelectElement("/IMAGE/NAME").Value; }
}
public string
ImageEditionId {
get { return XmlInfo.XPathSelectElement("/IMAGE/WINDOWS/EDITIONID").Value; }
}
public string
ImageFlags {
get { return XmlInfo.XPathSelectElement("/IMAGE/FLAGS").Value; }
}
public string
ImageProductType {
get {
return XmlInfo.XPathSelectElement("/IMAGE/WINDOWS/PRODUCTTYPE").Value;
}
}
public string
ImageInstallationType {
get { return XmlInfo.XPathSelectElement("/IMAGE/WINDOWS/INSTALLATIONTYPE").Value; }
}