1 //
2 // Copyright (c) 2010-2022 Antmicro
3 //
4 // This file is licensed under the MIT License.
5 // Full license text is available in 'licenses/MIT.txt'.
6 //
7 #if PLATFORM_WINDOWS
8 using System;
9 using System.IO;
10 using System.Threading;
11 using Antmicro.Renode.Logging;
12 
13 namespace Antmicro.Renode.Utilities
14 {
15     public class WindowsFileLocker : IDisposable
16     {
WindowsFileLocker(string fileToLock)17         public WindowsFileLocker(string fileToLock)
18         {
19             path = fileToLock;
20             var counter = 0;
21             while(true)
22             {
23                 try
24                 {
25                     file = File.Open(fileToLock, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None);
26                     return;
27                 }
28                 catch(IOException)
29                 {
30                     // ignore exception
31                 }
32 
33                 Thread.Sleep(500);
34                 counter++;
35                 if(counter == 10)
36                 {
37                     counter = 0;
38                     Logger.Log(LogLevel.Warning, "Still trying to lock file {0}", fileToLock);
39                 }
40             }
41         }
42 
Dispose()43         public void Dispose()
44         {
45             file.Close();
46             try
47             {
48                 File.Delete(path);
49             }
50             catch(IOException)
51             {
52                 // ignore exception
53             }
54         }
55 
56         private readonly FileStream file;
57         private readonly string path;
58     }
59 }
60 #endif
61