Paradox Game Engine  v1.0.0 beta06
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Events Macros Pages
TemporaryDirectory.cs
Go to the documentation of this file.
1 // Copyright (c) 2014 Silicon Studio Corp. (http://siliconstudio.co.jp)
2 // This file is distributed under GPL v3. See LICENSE.md for details.
3 #if SILICONSTUDIO_PLATFORM_WINDOWS_DESKTOP
4 using System;
5 using System.Diagnostics;
6 using System.IO;
7 
8 namespace SiliconStudio.Core.IO
9 {
10  public class TemporaryDirectory : IDisposable
11  {
12  private readonly string directoryPath;
13 
14  public TemporaryDirectory()
15  : this(Guid.NewGuid().ToString().Substring(0, 8))
16  {
17  }
18 
19  public TemporaryDirectory(string path)
20  {
21  this.directoryPath = Path.GetFullPath(path);
22 
23  if (Directory.Exists(this.directoryPath))
24  {
25  throw new InvalidOperationException(string.Format("Directory {0} already exists.", path));
26  }
27 
28  Directory.CreateDirectory(this.directoryPath);
29  }
30 
31  public string DirectoryPath
32  {
33  get { return directoryPath; }
34  }
35 
36  public void Dispose()
37  {
38  DeleteDirectory(directoryPath);
39  }
40 
41  public static void DeleteDirectory(string directoryPath)
42  {
43  // From http://stackoverflow.com/questions/329355/cannot-delete-directory-with-directory-deletepath-true/329502#329502
44 
45  if (!Directory.Exists(directoryPath))
46  {
47  Trace.WriteLine(
48  string.Format("Directory '{0}' is missing and can't be removed.",
49  directoryPath));
50 
51  return;
52  }
53 
54  string[] files = Directory.GetFiles(directoryPath);
55  string[] dirs = Directory.GetDirectories(directoryPath);
56 
57  foreach (string file in files)
58  {
59  File.SetAttributes(file, FileAttributes.Normal);
60  File.Delete(file);
61  }
62 
63  foreach (string dir in dirs)
64  {
65  DeleteDirectory(dir);
66  }
67 
68  try
69  {
70  File.SetAttributes(directoryPath, FileAttributes.Normal);
71  Directory.Delete(directoryPath, false);
72  }
73  catch (IOException)
74  {
75  Trace.WriteLine(string.Format("{0}The directory '{1}' could not be deleted!" +
76  "{0}Most of the time, this is due to an external process accessing the files in the temporary repositories created during the test runs, and keeping a handle on the directory, thus preventing the deletion of those files." +
77  "{0}Known and common causes include:" +
78  "{0}- Windows Search Indexer (go to the Indexing Options, in the Windows Control Panel, and exclude the bin folder of LibGit2Sharp.Tests)" +
79  "{0}- Antivirus (exclude the bin folder of LibGit2Sharp.Tests from the paths scanned by your real-time antivirus){0}",
80  Environment.NewLine, Path.GetFullPath(directoryPath)));
81  }
82  }
83  }
84 }
85 #endif