| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
using System; |
| 5 |
using System.IO; |
| 6 |
using System.Text; |
| 7 |
using System.Threading.Tasks; |
| 8 |
|
| 9 |
namespace Microsoft.NuGet.Build.Tasks.Tests.Helpers |
| 10 |
{ |
| 11 |
public class TempFile |
| 12 |
{ |
| 13 |
private readonly string _path; |
| 14 |
|
| 15 |
internal TempFile(string path) |
| 16 |
{ |
| 17 |
_path = path; |
| 18 |
} |
| 19 |
|
| 20 |
internal TempFile(TempRoot root, string prefix, string extension, string directory, string callerSourcePath, int callerLineNumber) |
| 21 |
{ |
| 22 |
while (true) |
| 23 |
{ |
| 24 |
if (prefix == null) |
| 25 |
{ |
| 26 |
prefix = System.IO.Path.GetFileName(callerSourcePath) + "_" + callerLineNumber.ToString() + "_"; |
| 27 |
} |
| 28 |
|
| 29 |
_path = System.IO.Path.Combine(directory ?? root.Root, prefix + Guid.NewGuid() + (extension ?? ".tmp")); |
| 30 |
|
| 31 |
try |
| 32 |
{ |
| 33 |
TempRoot.CreateStream(_path); |
| 34 |
break; |
| 35 |
} |
| 36 |
catch (PathTooLongException) |
| 37 |
{ |
| 38 |
throw; |
| 39 |
} |
| 40 |
catch (DirectoryNotFoundException) |
| 41 |
{ |
| 42 |
throw; |
| 43 |
} |
| 44 |
catch (IOException) |
| 45 |
{ |
| 46 |
|
| 47 |
} |
| 48 |
} |
| 49 |
} |
| 50 |
|
| 51 |
public FileStream Open(FileAccess access = FileAccess.ReadWrite) |
| 52 |
{ |
| 53 |
return new FileStream(_path, FileMode.Open, access); |
| 54 |
} |
| 55 |
|
| 56 |
public string Path |
| 57 |
{ |
| 58 |
get { return _path; } |
| 59 |
} |
| 60 |
|
| 61 |
public TempFile WriteAllText(string content, Encoding encoding) |
| 62 |
{ |
| 63 |
File.WriteAllText(_path, content, encoding); |
| 64 |
return this; |
| 65 |
} |
| 66 |
|
| 67 |
public TempFile WriteAllText(string content) |
| 68 |
{ |
| 69 |
File.WriteAllText(_path, content); |
| 70 |
return this; |
| 71 |
} |
| 72 |
|
| 73 |
public async Task<TempFile> WriteAllTextAsync(string content, Encoding encoding) |
| 74 |
{ |
| 75 |
using (var sw = new StreamWriter(File.Create(_path), encoding)) |
| 76 |
{ |
| 77 |
await sw.WriteAsync(content).ConfigureAwait(false); |
| 78 |
} |
| 79 |
|
| 80 |
return this; |
| 81 |
} |
| 82 |
|
| 83 |
public Task<TempFile> WriteAllTextAsync(string content) |
| 84 |
{ |
| 85 |
return WriteAllTextAsync(content, Encoding.UTF8); |
| 86 |
} |
| 87 |
|
| 88 |
public TempFile WriteAllBytes(byte[] content) |
| 89 |
{ |
| 90 |
File.WriteAllBytes(_path, content); |
| 91 |
return this; |
| 92 |
} |
| 93 |
|
| 94 |
public string ReadAllText() |
| 95 |
{ |
| 96 |
return File.ReadAllText(_path); |
| 97 |
} |
| 98 |
|
| 99 |
public TempFile CopyContentFrom(string path) |
| 100 |
{ |
| 101 |
return WriteAllBytes(File.ReadAllBytes(path)); |
| 102 |
} |
| 103 |
|
| 104 |
public override string ToString() |
| 105 |
{ |
| 106 |
return _path; |
| 107 |
} |
| 108 |
} |
| 109 |
} |