diff --git a/src/Microsoft.Windows.CsWin32/MetadataIndex.cs b/src/Microsoft.Windows.CsWin32/MetadataIndex.cs index 9a767b60..7c3a9072 100644 --- a/src/Microsoft.Windows.CsWin32/MetadataIndex.cs +++ b/src/Microsoft.Windows.CsWin32/MetadataIndex.cs @@ -250,11 +250,12 @@ internal static MetadataIndex Get(string metadataPath, Platform? platform) // Read the entire metadata file exactly once so that many MemoryStreams can share the memory. if (!MetadataFiles.TryGetValue(metadataPath, out MemoryMappedFile? file)) { - file = MemoryMappedFile.CreateFromFile(metadataPath); + FileStream metadataStream = new FileStream(metadataPath, FileMode.Open, FileAccess.Read, FileShare.Read); + file = MemoryMappedFile.CreateFromFile(metadataStream, mapName: null, capacity: 0, MemoryMappedFileAccess.Read, HandleInheritability.None, leaveOpen: false); MetadataFiles.Add(metadataPath, file); } - metadataBytes = file.CreateViewStream(); + metadataBytes = file.CreateViewStream(offset: 0, size: 0, MemoryMappedFileAccess.Read); } return new MetadataIndex(metadataPath, metadataBytes, platform); diff --git a/test/Microsoft.Windows.CsWin32.Tests/GeneratorTests.cs b/test/Microsoft.Windows.CsWin32.Tests/GeneratorTests.cs index 65ad7ec8..56412511 100644 --- a/test/Microsoft.Windows.CsWin32.Tests/GeneratorTests.cs +++ b/test/Microsoft.Windows.CsWin32.Tests/GeneratorTests.cs @@ -2429,6 +2429,14 @@ public void CocreatableStructs() Assert.Contains(classDecl.AttributeLists, al => al.Attributes.Any(a => a.Name.ToString().Contains("ComImport"))); } + [Fact] + public void OpensMetadataForSharedReading() + { + using FileStream competingReader = File.OpenRead(MetadataPath); + this.generator = this.CreateGenerator(); + Assert.True(this.generator.TryGenerate("CreateFile", CancellationToken.None)); + } + private static string ConstructGlobalConfigString(bool omitDocs = false) { StringBuilder globalConfigBuilder = new();