diff --git a/src/Nerdbank.GitVersioning.Tasks/AssemblyVersionInfo.cs b/src/Nerdbank.GitVersioning.Tasks/AssemblyVersionInfo.cs index 4ebfd5d0..a2b7b809 100644 --- a/src/Nerdbank.GitVersioning.Tasks/AssemblyVersionInfo.cs +++ b/src/Nerdbank.GitVersioning.Tasks/AssemblyVersionInfo.cs @@ -85,7 +85,9 @@ public override bool Execute() ns.Types.Add(this.CreateThisAssemblyClass()); Directory.CreateDirectory(Path.GetDirectoryName(this.OutputFile)); - using (var file = File.OpenWrite(this.OutputFile)) + FileStream file = null; + Utilities.FileOperationWithRetry(() => file = File.OpenWrite(this.OutputFile)); + using (file) { using (var fileWriter = new StreamWriter(file, new UTF8Encoding(true), 4096, leaveOpen: true)) { @@ -213,7 +215,8 @@ public override bool Execute() this.CreateThisAssemblyClass(); Directory.CreateDirectory(Path.GetDirectoryName(this.OutputFile)); - File.WriteAllText(this.OutputFile, this.generator.GetCode()); + string fileContent = this.generator.GetCode(); + Utilities.FileOperationWithRetry(() => File.WriteAllText(this.OutputFile, fileContent)); } return !this.Log.HasLoggedErrors; diff --git a/src/Nerdbank.GitVersioning.Tasks/NativeVersionInfo.cs b/src/Nerdbank.GitVersioning.Tasks/NativeVersionInfo.cs index 3cca8bd1..dd368626 100644 --- a/src/Nerdbank.GitVersioning.Tasks/NativeVersionInfo.cs +++ b/src/Nerdbank.GitVersioning.Tasks/NativeVersionInfo.cs @@ -124,7 +124,7 @@ public override bool Execute() this.generator.EndFile(); Directory.CreateDirectory(Path.GetDirectoryName(this.OutputFile)); - File.WriteAllText(this.OutputFile, this.generator.GetCode()); + Utilities.FileOperationWithRetry(() => File.WriteAllText(this.OutputFile, this.generator.GetCode())); } return !this.Log.HasLoggedErrors; diff --git a/src/Nerdbank.GitVersioning.Tasks/Utilities.cs b/src/Nerdbank.GitVersioning.Tasks/Utilities.cs new file mode 100644 index 00000000..9efe0c2d --- /dev/null +++ b/src/Nerdbank.GitVersioning.Tasks/Utilities.cs @@ -0,0 +1,31 @@ +using System; +using System.IO; +using System.Threading; +using System.Threading.Tasks; +using Validation; + +namespace Nerdbank.GitVersioning.Tasks +{ + internal static class Utilities + { + private const int ProcessCannotAccessFileHR = unchecked((int)0x80070020); + + internal static void FileOperationWithRetry(Action operation) + { + Requires.NotNull(operation, nameof(operation)); + + for (int retriesLeft = 6; retriesLeft > 0; retriesLeft--) + { + try + { + operation(); + } + catch (IOException ex) when (ex.HResult == ProcessCannotAccessFileHR && retriesLeft > 0) + { + Task.Delay(100).Wait(); + continue; + } + } + } + } +}