-
Notifications
You must be signed in to change notification settings - Fork 2
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #64 from linksplatform/FreePhoenix
Add TemporaryFiles, TemporaryFile
- Loading branch information
Showing
10 changed files
with
251 additions
and
9 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,35 @@ | ||
using Xunit; | ||
using System.IO; | ||
using System.Diagnostics; | ||
|
||
namespace Platform.IO.Tests | ||
{ | ||
public class TemporaryFileTests | ||
{ | ||
[Fact] | ||
public void TemporaryFileTest() | ||
{ | ||
using Process process = new(); | ||
process.StartInfo.FileName = Path.GetFullPath(Path.Combine(Directory.GetCurrentDirectory(), "..", "..", "..", "..", "TemporaryFileTest", "bin", "Debug", "net5", "TemporaryFileTest")); | ||
process.StartInfo.UseShellExecute = false; | ||
process.StartInfo.RedirectStandardOutput = true; | ||
process.Start(); | ||
var path = process.StandardOutput.ReadLine(); | ||
Assert.True(File.Exists(path)); | ||
process.WaitForExit(); | ||
Assert.False(File.Exists(path)); | ||
} | ||
|
||
[Fact] | ||
public void TemporaryFileTestWithoutConsoleApp() | ||
{ | ||
string fileName; | ||
using (TemporaryFile tempFile = new()) | ||
{ | ||
fileName = tempFile; | ||
Assert.True(File.Exists(fileName)); | ||
} | ||
Assert.False(File.Exists(fileName)); | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,62 @@ | ||
using Platform.Disposables; | ||
using System; | ||
using System.IO; | ||
using System.Runtime.CompilerServices; | ||
|
||
namespace Platform.IO | ||
{ | ||
/// <summary> | ||
/// <para>Represents a self-deleting temporary file.</para> | ||
/// <para>Представляет самоудаляющийся временный файл.</para> | ||
/// </summary> | ||
public class TemporaryFile : DisposableBase | ||
{ | ||
/// <summary> | ||
/// <para>Gets a temporary file path.</para> | ||
/// <para>Возвращает путь к временному файлу.</para> | ||
/// </summary> | ||
public readonly string Filename; | ||
|
||
/// <summary> | ||
/// <para>Converts the <see cref="TemporaryFile"/> instance to <see cref="string"/> using the <see cref="Filename"/> field value.</para> | ||
/// <para>Преобразует экземпляр <see cref="TemporaryFile"/> в <see cref="string"/> используя поле <see cref="Filename"/>.</para> | ||
/// </summary> | ||
/// <param name="file"> | ||
/// <para>A <see cref="TemporaryFile"/> instance.</para> | ||
/// <para>Экземпляр <see cref="TemporaryFile"/>.</para> | ||
/// </param> | ||
/// <returns> | ||
/// <para>Path to the temporary file.</para> | ||
/// <para>Путь к временному файлу.</para> | ||
/// </returns> | ||
public static implicit operator string(TemporaryFile file) => file.Filename; | ||
|
||
/// <summary> | ||
/// <para>Initializes a <see cref="TemporaryFile"/> instance.</para> | ||
/// <para>Инициализирует экземпляр класса <see cref="TemporaryFile"/>.</para> | ||
/// </summary> | ||
[MethodImpl(MethodImplOptions.AggressiveInlining)] | ||
public TemporaryFile() => Filename = TemporaryFiles.UseNew(); | ||
|
||
/// <summary> | ||
/// <para>Deletes the temporary file.</para> | ||
/// <para>Удаляет временный файл.</para> | ||
/// </summary> | ||
/// <param name="manual"> | ||
/// <para>A <see cref="Boolean"/> value that determines whether the disposal was triggered manually (by the developer's code) or was executed automatically without an explicit indication from a developer.</para> | ||
/// <para>Значение типа <see cref="Boolean"/>, определяющие было ли высвобождение вызвано вручную (кодом разработчика) или же выполнилось автоматически без явного указания со стороны разработчика.</para> | ||
/// </param> | ||
/// <param name="wasDisposed"> | ||
/// <para>A <see cref="Boolean"/> value that determines whether the <see cref="TemporaryFile"/> was released before a call to this method.</para> | ||
/// <para>Значение типа <see cref="Boolean"/>, определяющие были ли освобождены ресурсы, используемые <see cref="TemporaryFile"/> до вызова данного метода.</para> | ||
/// </param> | ||
[MethodImpl(MethodImplOptions.AggressiveInlining)] | ||
protected override void Dispose(bool manual, bool wasDisposed) | ||
{ | ||
if (!wasDisposed) | ||
{ | ||
File.Delete(Filename); | ||
} | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,60 @@ | ||
using System.IO; | ||
using System.Reflection; | ||
using System.Runtime.CompilerServices; | ||
|
||
namespace Platform.IO | ||
{ | ||
/// <summary> | ||
/// <para>Represents the set of helper methods to work with temporary files.</para> | ||
/// <para>Представляет набор вспомогательных методов для работы с временными файлами.</para> | ||
/// </summary> | ||
public class TemporaryFiles | ||
{ | ||
private const string UserFilesListFileNamePrefix = ".used-temporary-files.txt"; | ||
private static readonly object UsedFilesListLock = new(); | ||
private static readonly string UsedFilesListFilename = Assembly.GetExecutingAssembly().Location + UserFilesListFileNamePrefix; | ||
|
||
[MethodImpl(MethodImplOptions.AggressiveInlining)] | ||
private static void AddToUsedFilesList(string filename) | ||
{ | ||
lock (UsedFilesListLock) | ||
{ | ||
FileHelpers.AppendLine(UsedFilesListFilename, filename); | ||
} | ||
} | ||
|
||
/// <summary> | ||
/// <para>Gets a temporary file and adds it to the used files list.</para> | ||
/// <para>Получает временный файл и добавляет его в список использованных файлов.</para> | ||
/// </summary> | ||
/// <returns> | ||
/// <para>The temporary file path.</para> | ||
/// <para>Путь временного файла.</para> | ||
/// </returns> | ||
[MethodImpl(MethodImplOptions.AggressiveInlining)] | ||
public static string UseNew() | ||
{ | ||
var filename = Path.GetTempFileName(); | ||
AddToUsedFilesList(filename); | ||
return filename; | ||
} | ||
|
||
/// <summary> | ||
/// <para>Deletes all previously used temporary files and clears the files list.</para> | ||
/// <para>Удаляет все ранее использованные временные файлы и очищает список файлов.</para> | ||
/// </summary> | ||
[MethodImpl(MethodImplOptions.AggressiveInlining)] | ||
public static void DeleteAllPreviouslyUsed() | ||
{ | ||
lock (UsedFilesListLock) | ||
{ | ||
var listFilename = UsedFilesListFilename; | ||
if (File.Exists(listFilename)) | ||
{ | ||
FileHelpers.EachLine(listFilename, File.Delete); | ||
FileHelpers.Truncate(listFilename); | ||
} | ||
} | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,16 @@ | ||
using System; | ||
using Platform.IO; | ||
using System.IO; | ||
using System.Reflection; | ||
|
||
namespace TemporaryFileTest | ||
{ | ||
class Program | ||
{ | ||
static void Main() | ||
{ | ||
using TemporaryFile tempFile = new(); | ||
Console.WriteLine(tempFile); | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,12 @@ | ||
<Project Sdk="Microsoft.NET.Sdk"> | ||
|
||
<PropertyGroup> | ||
<OutputType>Exe</OutputType> | ||
<TargetFramework>net5</TargetFramework> | ||
</PropertyGroup> | ||
|
||
<ItemGroup> | ||
<ProjectReference Include="..\Platform.IO\Platform.IO.csproj" /> | ||
</ItemGroup> | ||
|
||
</Project> |