System.IO.DirectoryInfo.Delete()

Here are the examples of the csharp api System.IO.DirectoryInfo.Delete() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

80 Examples 7

19 Source : AssetBundleUtil.cs
with MIT License
from 404Lcc

public static void BuildreplacedetBundle(replacedetBundleSetting replacedetBundleSetting)
        {
            Dictionary<string, replacedetBundleData> replacedetBundleDataDict = new Dictionary<string, replacedetBundleData>();
            Dictionary<string, replacedetBundleRuleType> replacedetBundleRuleTypeDict = new Dictionary<string, replacedetBundleRuleType>();
            string path = PathUtil.GetPath(PathType.DataPath, replacedetBundleSetting.outputPath, GetPlatformForreplacedetBundle(EditorUserBuildSettings.activeBuildTarget));
            foreach (DirectoryInfo item in DirectoryUtil.GetDirectorys(new DirectoryInfo(path), new List<DirectoryInfo>()))
            {
                item.Delete();
            }
            foreach (FileInfo item in FileUtil.GetFiles(new DirectoryInfo(path), new List<FileInfo>()))
            {
                item.Delete();
            }
            List<replacedetBundleBuild> replacedetBundleBuildList = new List<replacedetBundleBuild>();
            foreach (replacedetBundleRule item in replacedetBundleSetting.replacedetBundleRuleList)
            {
                if (item.replacedetBundleRuleType == replacedetBundleRuleType.File)
                {
                    FileInfo[] fileInfos = FileUtil.GetFiles(new DirectoryInfo(item.path), new List<FileInfo>());
                    if (fileInfos.Length == 0) continue;
                    List<FileInfo> fileInfoList = (from fileInfo in fileInfos where !string.IsNullOrEmpty(Path.GetExtension(fileInfo.Name)) && Path.GetExtension(fileInfo.Name) != ".meta" select fileInfo).ToList();
                    foreach (FileInfo fileInfo in fileInfoList)
                    {
                        replacedetBundleRuleTypeDict.Add(fileInfo.FullName.Substring(fileInfo.FullName.IndexOf("replacedets")).Replace("\\", "/"), replacedetBundleRuleType.File);
                    }
                }
                if (item.replacedetBundleRuleType == replacedetBundleRuleType.Directory)
                {
                    DirectoryInfo[] directoryInfos = DirectoryUtil.GetDirectorys(new DirectoryInfo(item.path), new List<DirectoryInfo>());
                    if (directoryInfos.Length == 0) continue;
                    foreach (DirectoryInfo directoryInfo in directoryInfos)
                    {
                        FileInfo[] fileInfos = directoryInfo.GetFiles();
                        if (fileInfos.Length == 0) continue;
                        List<FileInfo> fileInfoList = (from fileInfo in fileInfos where !string.IsNullOrEmpty(Path.GetExtension(fileInfo.Name)) && Path.GetExtension(fileInfo.Name) != ".meta" select fileInfo).ToList();
                        foreach (FileInfo fileInfo in fileInfoList)
                        {
                            replacedetBundleRuleTypeDict.Add(fileInfo.FullName.Substring(fileInfo.FullName.IndexOf("replacedets")).Replace("\\", "/"), replacedetBundleRuleType.Directory);
                        }
                    }
                }
            }
            foreach (replacedetBundleData item in replacedetBundleSetting.replacedetBundleDataList)
            {
                replacedetBundleBuildList.Add(new replacedetBundleBuild()
                {
                    replacedetBundleName = item.replacedetBundleName,
                    replacedetNames = item.replacedetNames,
                });
            }
            replacedetBundleManifest replacedetBundleManifest = BuildPipeline.BuildreplacedetBundles(path, replacedetBundleBuildList.ToArray(), BuildreplacedetBundleOptions.None, EditorUserBuildSettings.activeBuildTarget);
            foreach (replacedetBundleData item in replacedetBundleSetting.replacedetBundleDataList)
            {
                item.replacedetBundleHash = replacedetBundleManifest.GetreplacedetBundleHash(item.replacedetBundleName).ToString();
                BuildPipeline.GetCRCForreplacedetBundle($"{path}/{item.replacedetBundleName}", out item.replacedetBundleCRC);
                item.fileSize = FileUtil.GetFileSize($"{path}/{item.replacedetBundleName}");
                replacedetBundleDataDict.Add(Path.GetFileNameWithoutExtension(item.replacedetBundleName), item);
            }
            replacedetBundleConfig replacedetBundleConfig = new replacedetBundleConfig(replacedetBundleSetting.buildId, replacedetBundleDataDict, replacedetBundleRuleTypeDict);
            FileUtil.Savereplacedet(path, "replacedetBundleConfig.json", JsonUtil.ToJson(replacedetBundleConfig));
            if (replacedetBundleSetting.isCopyStreamingreplacedets)
            {
                string copyPath = PathUtil.GetPath(PathType.StreamingreplacedetsPath, "Res", GetPlatformForreplacedetBundle(EditorUserBuildSettings.activeBuildTarget));
                foreach (DirectoryInfo item in DirectoryUtil.GetDirectorys(new DirectoryInfo(copyPath), new List<DirectoryInfo>()))
                {
                    item.Delete();
                }
                foreach (FileInfo item in FileUtil.GetFiles(new DirectoryInfo(copyPath), new List<FileInfo>()))
                {
                    item.Delete();
                }
                foreach (FileInfo item in FileUtil.GetFiles(new DirectoryInfo(path), new List<FileInfo>()))
                {
                    if (Path.GetExtension(item.Name) == ".meta") continue;
                    File.Copy(item.FullName, $"{PathUtil.GetPath(PathType.StreamingreplacedetsPath, "Res", GetPlatformForreplacedetBundle(EditorUserBuildSettings.activeBuildTarget))}/{item.Name}");
                }
            }
            replacedetDatabase.Refresh();
        }

19 Source : GameDataManager.cs
with MIT License
from 404Lcc

public void DeleteAll()
        {
            DirectoryInfo directoryInfo = new DirectoryInfo(PathUtil.GetPath(PathType.PersistentDataPath, "Res"));
            if (directoryInfo.Exists)
            {
                directoryInfo.Delete();
                userData = null;
                userSetData = null;
            }
        }

19 Source : IOUtil.cs
with MIT License
from actions

public static void DeleteDirectory(string path, bool contentsOnly, bool continueOnContentDeleteError, CancellationToken cancellationToken)
        {
            ArgUtil.NotNullOrEmpty(path, nameof(path));
            DirectoryInfo directory = new DirectoryInfo(path);
            if (!directory.Exists)
            {
                return;
            }

            if (!contentsOnly)
            {
                // Remove the readonly flag.
                RemoveReadOnly(directory);

                // Check if the directory is a reparse point.
                if (directory.Attributes.HasFlag(FileAttributes.ReparsePoint))
                {
                    // Delete the reparse point directory and short-circuit.
                    directory.Delete();
                    return;
                }
            }

            // Initialize a concurrent stack to store the directories. The directories
            // cannot be deleted until the files are deleted.
            var directories = new ConcurrentStack<DirectoryInfo>();

            if (!contentsOnly)
            {
                directories.Push(directory);
            }

            // Create a new token source for the parallel query. The parallel query should be
            // canceled after the first error is encountered. Otherwise the number of exceptions
            // could get out of control for a large directory with access denied on every file.
            using (var tokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken))
            {
                try
                {
                    // Recursively delete all files and store all subdirectories.
                    Enumerate(directory, tokenSource)
                        .AsParallel()
                        .WithCancellation(tokenSource.Token)
                        .ForAll((FileSystemInfo item) =>
                        {
                            bool success = false;
                            try
                            {
                                // Remove the readonly attribute.
                                RemoveReadOnly(item);

                                // Check if the item is a file.
                                if (item is FileInfo)
                                {
                                    // Delete the file.
                                    item.Delete();
                                }
                                else
                                {
                                    // Check if the item is a directory reparse point.
                                    var subdirectory = item as DirectoryInfo;
                                    ArgUtil.NotNull(subdirectory, nameof(subdirectory));
                                    if (subdirectory.Attributes.HasFlag(FileAttributes.ReparsePoint))
                                    {
                                        try
                                        {
                                            // Delete the reparse point.
                                            subdirectory.Delete();
                                        }
                                        catch (DirectoryNotFoundException)
                                        {
                                            // The target of the reparse point directory has been deleted.
                                            // Therefore the item is no longer a directory and is now a file.
                                            //
                                            // Deletion of reparse point directories happens in parallel. This case can occur
                                            // when reparse point directory FOO points to some other reparse point directory BAR,
                                            // and BAR is deleted after the DirectoryInfo for FOO has already been initialized.
                                            File.Delete(subdirectory.FullName);
                                        }
                                    }
                                    else
                                    {
                                        // Store the directory.
                                        directories.Push(subdirectory);
                                    }
                                }

                                success = true;
                            }
                            catch (Exception) when (continueOnContentDeleteError)
                            {
                                // ignore any exception when continueOnContentDeleteError is true.
                                success = true;
                            }
                            finally
                            {
                                if (!success)
                                {
                                    tokenSource.Cancel(); // Cancel is thread-safe.
                                }
                            }
                        });
                }
                catch (Exception)
                {
                    tokenSource.Cancel();
                    throw;
                }
            }

            // Delete the directories.
            foreach (DirectoryInfo dir in directories.OrderByDescending(x => x.FullName.Length))
            {
                cancellationToken.ThrowIfCancellationRequested();
                dir.Delete();
            }
        }

19 Source : IOUtilL0.cs
with MIT License
from actions

[Fact]
        [Trait("Level", "L0")]
        [Trait("Category", "Common")]
        public void DeleteDirectory_DeletesReadOnlyRootDirectory()
        {
            using (TestHostContext hc = new TestHostContext(this))
            {
                Tracing trace = hc.GetTrace();

                // Arrange: Create a read-only directory.
                string directory = Path.Combine(hc.GetDirectory(WellKnownDirectory.Bin), Path.GetRandomFileName());
                try
                {
                    var directoryInfo = new DirectoryInfo(directory);
                    directoryInfo.Create();
                    directoryInfo.Attributes = directoryInfo.Attributes | FileAttributes.ReadOnly;

                    // Act.
                    IOUtil.DeleteDirectory(directory, CancellationToken.None);

                    // replacedert.
                    replacedert.False(Directory.Exists(directory));
                }
                finally
                {
                    // Cleanup.
                    var directoryInfo = new DirectoryInfo(directory);
                    if (directoryInfo.Exists)
                    {
                        directoryInfo.Attributes = directoryInfo.Attributes & ~FileAttributes.ReadOnly;
                        directoryInfo.Delete();
                    }
                }
            }
        }

19 Source : ModDownloader.cs
with GNU General Public License v3.0
from amakvana

private void DeleteModData(string path)
        {
            DirectoryInfo dir = new DirectoryInfo(path);

            foreach (FileInfo fi in dir.GetFiles())
            {
                fi.Delete();
            }

            foreach (DirectoryInfo di in dir.GetDirectories())
            {
                DeleteModData(di.FullName);
                di.Delete();
            }
        }

19 Source : Factorio.cs
with GNU General Public License v3.0
from Artentus

public static async Task<(bool, IFactorioInstance?)> TryExtract(FileInfo archiveFile, string destination, string? dirName = null)
        {
            var destinationDir = new DirectoryInfo(destination);
            if (!destinationDir.Exists) destinationDir.Create();

            var (valid, extractName) = await Task.Run(() =>
            {
                if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
                {
                    return ExtractWin32(archiveFile, destination);
                }
                else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
                {
                    return ExtractLinux(archiveFile, destination);
                }
                else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
                {
                    return ExtractMac(archiveFile, destination);
                }
                else
                {
                    throw new PlatformNotSupportedException();
                }
            });

            if (!valid)
            {
                if (!string.IsNullOrEmpty(extractName))
                {
                    // We may have extracted some files already, but they must
                    // all reside in a directory called 'Factorio_*' so we can
                    // clean up easily.
                    var dir = destinationDir.EnumerateDirectories(extractName).FirstOrDefault();
                    if (!(dir is null)) dir.Delete(true);
                }

                return (false, null);
            }
            else
            {
                var dir = destinationDir.EnumerateDirectories(extractName).First(); // Must exist
                if (!string.IsNullOrEmpty(dirName))
                    dir.MoveTo(Path.Combine(dir.Parent.FullName, dirName));

                var (success, instance) = await TryLoadAsync(dir);
                if (!success) dir.Delete();
                return (success, instance);
            }
        }

19 Source : DirectoryInfoExtensions.cs
with GNU General Public License v3.0
from Artentus

public static async Task<DirectoryInfo> MoveToAsync(this DirectoryInfo directory, string path)
        {
            var root1 = Path.GetPathRoot(directory.FullName);
            var root2 = Path.GetPathRoot(path);
            if (string.Equals(root1, root2, StringComparison.OrdinalIgnoreCase)) // Functionality integrated
            {
                directory.MoveTo(path);
                return directory;
            }
            else // Moving all files one-by-one
            {
                var newDir = new DirectoryInfo(path);
                if (!newDir.Exists) newDir.Create();

                foreach (var file in directory.EnumerateFiles())
                    await file.MoveToAsync(Path.Combine(newDir.FullName, file.Name));

                foreach (var subDir in directory.EnumerateDirectories())
                    await MoveToAsync(subDir, Path.Combine(newDir.FullName, subDir.Name));

                directory.Delete();
                return newDir;
            }
        }

19 Source : ModTekCacheStorage.cs
with The Unlicense
from BattletechModders

internal static void CleanModTekTempDir(DirectoryInfo baseDir)
        {
            if (!baseDir.Exists)
            {
                return;
            }

            foreach (var dir in baseDir.EnumerateDirectories())
            {
                CleanModTekTempDir(dir);
            }

            foreach (var file in baseDir.EnumerateFiles())
            {
                file.IsReadOnly = false;
                Log("delete file " + file.FullName);
                try
                {
                    file.Delete();
                }
                catch (Exception)
                {
                    // ignored
                }
            }

            Log("delete directory " + baseDir.FullName);
            try
            {
                baseDir.Delete();
            }
            catch (Exception)
            {
                // ignored
            }
        }

19 Source : RemoveItemCommand.cs
with BSD 3-Clause "New" or "Revised" License
from bitsadmin

private static void DirectoryDelete(string dirName, bool recurse, bool force)
        {
            // Get the subdirectories for the specified directory.
            DirectoryInfo dir = new DirectoryInfo(dirName);
            DirectoryInfo[] dirs = dir.GetDirectories();

            if (dirs.Length > 0 && !recurse)
                throw new System.Exception(string.Format("The item at {0} has children and the Recurse parameter was not specified. Nothing has been removed.", dirName));

            // Get the files in the directory and copy them to the new location.
            FileInfo[] files = dir.GetFiles();
            foreach (FileInfo file in files)
            {
                // Remove readonly attribute
                if (force)
                    File.SetAttributes(file.FullName, file.Attributes & ~FileAttributes.ReadOnly);

                file.Delete();
            }

            // Remove subdirectories and their contents if Recurse flag is set
            if (recurse)
            {
                foreach (DirectoryInfo subdir in dirs)
                {
                    DirectoryDelete(subdir.FullName, recurse, force);
                    subdir.Delete();
                }
            }
        }

19 Source : PackageConfigurationUpdater.cs
with MIT License
from bonsai-rx

void RemoveEmptyDirectories(DirectoryInfo directory)
        {
            try
            {
                foreach (var subdirectory in directory.EnumerateDirectories())
                {
                    RemoveEmptyDirectories(subdirectory);
                }

                if (!directory.EnumerateFileSystemInfos().Any())
                {
                    try { directory.Delete(); }
                    catch (UnauthorizedAccessException) { } //best effort
                }
            }
            catch (DirectoryNotFoundException) { } //best effort
            catch (UnauthorizedAccessException) { } //best effort
        }

19 Source : PackageManager.cs
with MIT License
from bonsai-rx

static void DeleteDirectoryTree(DirectoryInfo directory)
        {
            foreach (var subdirectory in directory.GetDirectories())
            {
                DeleteDirectoryTree(subdirectory);
            }

            try { directory.Delete(); }
            catch (IOException) { }
            catch (UnauthorizedAccessException) { }
        }

19 Source : ApiService.cs
with MIT License
from chatop2020

public static bool CleanUpEmptyDir(out ResponseStruct rs, string rootPath = "")
        {
            rs = new ResponseStruct()
            {
                Code = ErrorNumber.None,
                Message = ErrorMessage.ErrorDic![ErrorNumber.None],
            };
            if (string.IsNullOrEmpty(rootPath))
            {
                foreach (var path in Common.AkStreamKeeperConfig.CustomRecordPathList)
                {
                    string dirList = "";
                    if (!string.IsNullOrEmpty(path) && Directory.Exists(path))
                    {
                        try
                        {
                            DirectoryInfo dir = new DirectoryInfo(path);
                            DirectoryInfo[] subdirs = dir.GetDirectories("*.*", SearchOption.AllDirectories);
                            foreach (DirectoryInfo subdir in subdirs)
                            {
                                FileSystemInfo[] subFiles = subdir.GetFileSystemInfos();
                                var l = subFiles.Length;
                                if (l == 0)
                                {
                                    subdir.Delete();
                                    dirList += "清理空目录 ->" + subdir + "\r\n";
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            Logger.Error($@"[{Common.LoggerHead}]->清理空目录时发生异常->{ex.Message}\r\n{ex.StackTrace}");
                        }

                        if (!string.IsNullOrEmpty(dirList))
                        {
                            Logger.Info($@"[{Common.LoggerHead}]->{dirList}");
                        }
                    }
                }
            }
            else
            {
                string dirList = "";
                if (!string.IsNullOrEmpty(rootPath) && Directory.Exists(rootPath))
                {
                    try
                    {
                        DirectoryInfo dir = new DirectoryInfo(rootPath);
                        DirectoryInfo[] subdirs = dir.GetDirectories("*.*", SearchOption.AllDirectories);
                        foreach (DirectoryInfo subdir in subdirs)
                        {
                            FileSystemInfo[] subFiles = subdir.GetFileSystemInfos();
                            var l = subFiles.Length;
                            if (l == 0)
                            {
                                subdir.Delete();
                                dirList += "清理空目录 ->" + subdir + "\r\n";
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        Logger.Error($@"[{Common.LoggerHead}]->清理空目录时发生异常->{ex.Message}\r\n{ex.StackTrace}");
                    }

                    if (!string.IsNullOrEmpty(dirList))
                    {
                        Logger.Info($@"[{Common.LoggerHead}]->{dirList}");
                    }
                }
            }

            return true;
        }

19 Source : UpdateDialog.cs
with MIT License
from CityOfZion

private void Web_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
        {
            if (e.Cancelled || e.Error != null) return;
            DirectoryInfo di = new DirectoryInfo("update");
            if (di.Exists) di.Delete(true);
            di.Create();
            ZipFile.ExtractToDirectory(download_path, di.Name);
            FileSystemInfo[] fs = di.GetFileSystemInfos();
            if (fs.Length == 1 && fs[0] is DirectoryInfo)
            {
                ((DirectoryInfo)fs[0]).MoveTo("update2");
                di.Delete();
                Directory.Move("update2", di.Name);
            }
            File.WriteAllBytes("update.bat", Resources.UpdateBat);
            Close();
            if (Program.MainForm != null) Program.MainForm.Close();
            Process.Start("update.bat");
        }

19 Source : ImageFileCache.cs
with Microsoft Public License
from ClemensFischer

private static int CleanDirectory(DirectoryInfo directory)
        {
            var deletedFileCount = 0;

            try
            {
                deletedFileCount += directory.EnumerateDirectories().Sum(dir => CleanDirectory(dir));

                deletedFileCount += directory.EnumerateFiles().Sum(file => CleanFile(file));

                if (!directory.EnumerateFileSystemInfos().Any())
                {
                    directory.Delete();
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"ImageFileCache: Failed cleaning {directory.FullName}: {ex.Message}");
            }

            return deletedFileCount;
        }

19 Source : System_IO_DirectoryInfo_Binding.cs
with MIT License
from CragonGame

static StackObject* Delete_13(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj)
        {
            ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain;
            StackObject* ptr_of_this_method;
            StackObject* __ret = ILIntepreter.Minus(__esp, 1);

            ptr_of_this_method = ILIntepreter.Minus(__esp, 1);
            System.IO.DirectoryInfo instance_of_this_method = (System.IO.DirectoryInfo)typeof(System.IO.DirectoryInfo).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
            __intp.Free(ptr_of_this_method);

            instance_of_this_method.Delete();

            return __ret;
        }

19 Source : AssetScriptReferenceRetargeter.cs
with MIT License
from cre8ivepark

private static void RecursiveFolderCleanup(DirectoryInfo folder)
        {
            foreach (DirectoryInfo subFolder in folder.GetDirectories())
            {
                RecursiveFolderCleanup(subFolder);
            }

            FileInfo[] fileList = folder.GetFiles("*");
            DirectoryInfo[] folderList = folder.GetDirectories();
            foreach (FileInfo file in fileList)
            {
                if (file.Extension.Equals(".meta"))
                {
                    string nameCheck = file.FullName.Remove(file.FullName.Length - 5);

                    // If we don't have any files or folders match the nameCheck we will delete the file
                    if (!fileList.Concat<FileSystemInfo>(folderList).Any(t => nameCheck.Equals(t.FullName)))
                    {
                        file.Delete();
                    }
                }
            }

            if (folder.GetDirectories().Length == 0 && folder.GetFiles().Length == 0)
            {
                folder.Delete();
            }
        }

19 Source : Helpers.cs
with GNU General Public License v3.0
from cryptoprofitswitcher

internal static string GetJsonFromUrl(string url, bool enableCaching, DirectoryInfo appRootFolder, CancellationToken ct)
        {
            DirectoryInfo cacheFolder = null;
            if (appRootFolder != null)
            {
                cacheFolder = appRootFolder.CreateSubdirectory("Cache");
            }
            string responseBody;
            try
            {
                using var client = new HttpClient(new HttpClientHandler() { AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate });
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                client.DefaultRequestHeaders.UserAgent.TryParseAdd("request");
                HttpResponseMessage response = client.GetAsync(new Uri(url), ct).Result;

                response.EnsureSuccessStatusCode();

                using HttpContent content = response.Content;
                responseBody = response.Content.ReadreplacedtringAsync().Result;
                //Save to cache
                if (enableCaching && !url.Contains("127.0.0.1", StringComparison.InvariantCulture))
                {
                    int tries = 0;
                    while (tries < 2)
                    {
                        tries++;
                        try
                        {
                            string hashedFilename = CreateMd5(url) + ".json";
                            if (cacheFolder != null)
                            {
                                string savePath = Path.Combine(cacheFolder.FullName, hashedFilename);
                                _lock.EnterWriteLock();
                                File.WriteAllText(savePath, responseBody);
                            }

                            _lock.ExitWriteLock();
                        }
                        catch (Exception ex)
                        {
                            Log.Debug("Couldn't save to cache: " + ex);
                            // Reset Cache
                            _lock.EnterWriteLock();
                            cacheFolder?.Delete();
                            _lock.ExitWriteLock();
                        }
                    }
                }
                return responseBody;
            }
            catch (Exception ex)
            {
                Log.Debug("Couldn't get data from: " + url);
                Log.Debug("Error message: " + ex.Message);

                //Try to get from cache
                if (cacheFolder != null)
                {
                    string hashedFilename = CreateMd5(url) + ".json";
                    var cachedFile = cacheFolder.GetFiles(hashedFilename).First();
                    var cachedContent = File.ReadAllText(cachedFile.FullName);
                    Console.WriteLine("Got data from cache.");
                    return cachedContent;
                }
                throw;
            }
        }

19 Source : FileExtensions.cs
with Apache License 2.0
from cs-util-com

public static bool DeleteV2(this DirectoryInfo self, bool deleteAlsoIfNotEmpty = true) {
            return DeleteV2(self, () => {
                if (deleteAlsoIfNotEmpty) { // Recursively delete all children first:
                    if (!self.IsEmtpy()) {
                        foreach (var subDir in self.GetDirectories()) { subDir.DeleteV2(deleteAlsoIfNotEmpty); }
                        foreach (var file in self.GetFiles()) { file.DeleteV2(); }
                    }
                }
                self.Refresh();
                if (!self.IsEmtpy()) { throw new IOException("Cant delete non-emtpy dir: " + self.FullPath()); }
                try { self.Delete(); return true; } catch (Exception e) { Log.e(e); }
                return false;
            });
        }

19 Source : GamePassCatalogBrowserService.cs
with MIT License
from darklinkpower

private void ClearFolder(string folderPath)
        {
            DirectoryInfo dir = new DirectoryInfo(folderPath);

            foreach (FileInfo file in dir.GetFiles())
            {
                file.Delete();
            }

            foreach (DirectoryInfo directory in dir.GetDirectories())
            {
                ClearFolder(directory.FullName);
                directory.Delete();
            }
        }

19 Source : CreateFolderAction.cs
with MIT License
from DCourtel

[TestMethod]
            public void CreateTheFolder_WhenFolderDoesNotExists()
            {
                // Arrange
                SUT action = new SUT(Tools.GetXmlFragment("CreateFolderAction.CustAct"));
                DirectoryInfo newDirectory = new DirectoryInfo(action.FullPath);
                var finalResult = Tools.GetReturnCodeAction();

                // Act
                if (newDirectory.Exists)
                {
                    newDirectory.Delete();
                    newDirectory = new DirectoryInfo(action.FullPath);
                    replacedert.IsFalse(newDirectory.Exists);
                }

                action.Run(ref finalResult);
                newDirectory = new DirectoryInfo(action.FullPath);

                // replacedert
                replacedert.IsTrue(newDirectory.Exists);
            }

19 Source : RenameFolderAction.cs
with MIT License
from DCourtel

[TestMethod]
            public void RenameTheFile_WhenCalled()
            {
                // Arrange
                SUT action = new SUT(Tools.GetXmlFragment("RenameFolder.CustAct"));
                var finalResult = Tools.GetReturnCodeAction();
                DirectoryInfo folderToRename = new DirectoryInfo(action.FolderPath);
                DirectoryInfo renamedFolder = new DirectoryInfo(Path.Combine(folderToRename.Parent.FullName, action.NewName));

                if (!folderToRename.Parent.Exists)
                {
                    folderToRename.Parent.Create();
                }
                if (!folderToRename.Exists)
                {
                    folderToRename.Create();
                }
                if(renamedFolder.Exists)
                {
                    renamedFolder.Delete();
                    renamedFolder.Refresh();
                }

                folderToRename.Refresh();
                replacedert.IsTrue(folderToRename.Exists);
                replacedert.IsFalse(renamedFolder.Exists);

                // Act
                action.Run(ref finalResult);
                folderToRename.Refresh();
                renamedFolder.Refresh();

                // replacedert
                replacedert.IsFalse(folderToRename.Exists);
                replacedert.IsTrue(renamedFolder.Exists);
            }

19 Source : Program.cs
with Microsoft Public License
from Dijji

private static void ExportFolder(XstFile xstFile, Folder folder, Command command, string exportDir)
        {
            if (folder.ContentCount == 0)
            {
                Console.WriteLine($"Skipping folder '{folder.Name}', which is empty");
                return;
            }

            bool createdByUs = false;
            if (!Directory.Exists(exportDir))
            {
                Directory.CreateDirectory(exportDir);
                createdByUs = true;
            }

            switch (command)
            {
                case Command.Email:
                    ExtractEmailsInFolder(xstFile, folder, exportDir);
                    break;
                case Command.Properties:
                    ExtractPropertiesInFolder(xstFile, folder, exportDir);
                    break;
                case Command.Attachments:
                    ExtractAttachmentsInFolder(xstFile, folder, exportDir);
                    break;
                case Command.Help:
                default:
                    break;
            }

            // If we create the directory, clean it up if nothing is put in it
            if (createdByUs)
            {
                var di = new DirectoryInfo(exportDir);
                if (!di.EnumerateFiles().Any() &&
                    !di.EnumerateDirectories().Any())
                    di.Delete();
            }
        }

19 Source : Utility.IO.cs
with MIT License
from DonnYep

public static void DeleteFolder(string folderPath)
            {
                if (Directory.Exists(folderPath))
                {
                    DirectoryInfo directory = Directory.CreateDirectory(folderPath);
                    FileInfo[] files = directory.GetFiles();
                    foreach (var file in files)
                    {
                        file.Delete();
                    }
                    DirectoryInfo[] folders = directory.GetDirectories();
                    foreach (var folder in folders)
                    {
                        DeleteFolder(folder.FullName);
                    }
                    directory.Delete();
                }
            }

19 Source : DirectoryInfoExtensions.cs
with MIT License
from dotnet-toolbelt

public static void DeleteOlderThan(this DirectoryInfo obj, TimeSpan timeSpan)
        {
            DateTime minDate = DateTime.Now.Subtract(timeSpan);
            obj.GetFiles().Where(x => x.LastWriteTime < minDate).ToList().ForEach(x => x.Delete());
            obj.GetDirectories().Where(x => x.LastWriteTime < minDate).ToList().ForEach(x => x.Delete());
        }

19 Source : DirectoryInfoExtensions.cs
with MIT License
from dotnet-toolbelt

public static void DeleteOlderThan(this DirectoryInfo obj, SearchOption searchOption, TimeSpan timeSpan)
        {
            DateTime minDate = DateTime.Now.Subtract(timeSpan);
            obj.GetFiles("*.*", searchOption).Where(x => x.LastWriteTime < minDate).ToList().ForEach(x => x.Delete());
            obj.GetDirectories("*.*", searchOption).Where(x => x.LastWriteTime < minDate).ToList().ForEach(x => x.Delete());
        }

19 Source : FileMan.cs
with GNU Affero General Public License v3.0
from Flare-Client

public void resetConfig()
        {
            if (configFile.Exists)
            {
                configFile.Delete();
            }
            if (configDir.Exists)
            {
                configDir.Delete();
            }
            saveConfig();
        }

19 Source : ServerManager.cs
with MIT License
from ForkGG

private bool MoveEnreplacedies(string newPath)
        {
            DirectoryInfo newDir = new DirectoryInfo(newPath);
            if (!newDir.Exists)
            {
                ErrorLogger.Append(new Exception("Can't move Servers/Networks to not existing dir: " + newPath));
                return false;
            }

            DirectoryInfo test = new DirectoryInfo(Path.Combine(newDir.FullName, "test"));
            test.Create();
            test.Delete();

            foreach (EnreplacedyViewModel enreplacedyViewModel in Enreplacedies)
            {
                string currEnreplacedyPath = Path.Combine(App.ServerPath, enreplacedyViewModel.Enreplacedy.Name);
                string newEnreplacedyPath = Path.Combine(newPath, enreplacedyViewModel.Enreplacedy.Name);

                enreplacedyViewModel.StartImport();
                new Thread(() =>
                {
                    //Directory.Move(currEnreplacedyPath,newEnreplacedyPath);
                    FileImporter fileImporter = new FileImporter();
                    fileImporter.CopyProgressChanged += enreplacedyViewModel.CopyProgressChanged;
                    fileImporter.DirectoryMove(currEnreplacedyPath, newEnreplacedyPath, true);
                    Console.WriteLine("Finished moving enreplacedy files for enreplacedy " + enreplacedyViewModel.Name);
                    enreplacedyViewModel.FinishedCopying();
                }).Start();
            }

            AppSettingsSerializer.Instance.AppSettings.ServerPath = newPath;
            AppSettingsSerializer.Instance.SaveSettings();
            return true;
        }

19 Source : RunSetsExecutionsHistoryPage.xaml.cs
with Apache License 2.0
from Ginger-Automation

private void DeleteSelectedExecutionResults(object sender, System.Windows.RoutedEventArgs e)
        {
            if ((Reporter.ToUser(eUserMsgKey.ExecutionsResultsToDelete)) == Amdocs.Ginger.Common.eUserMsgSelection.Yes)
            {
                foreach (RunSetReport runSetReport in grdExecutionsHistory.Grid.SelectedItems)
                {
                    if (runSetReport.DataRepMethod == ExecutionLoggerConfiguration.DataRepositoryMethod.LiteDB)
                    {
                        LiteDbManager dbManager = new LiteDbManager(WorkSpace.Instance.Solution.LoggerConfigurations.CalculatedLoggerFolder);
                        var result = dbManager.GetRunSetLiteData();
                        List<LiteDbRunSet> filterData = null;
                        filterData = result.IncludeAll().Find(a => a._id.ToString() == runSetReport.GUID).ToList();
                        
                        LiteDbConnector dbConnector = new LiteDbConnector(Path.Combine(mRunSetExecsRootFolder, "GingerExecutionResults.db"));
                        dbConnector.DeleteDoreplacedentByLiteDbRunSet(filterData[0]);
                        break;
                    }
                    string runSetFolder = executionLoggerHelper.GetLoggerDirectory(runSetReport.LogFolder);

                    var fi = new DirectoryInfo(runSetFolder);
                    CleanDirectory(fi.FullName);
                    fi.Delete();
                }

                if (grdExecutionsHistory.Grid.SelectedItems.Count > 0)
                {
                    LoadExecutionsHistoryData();
                }
            }
        }

19 Source : RunSetsExecutionsHistoryPage.xaml.cs
with Apache License 2.0
from Ginger-Automation

private void DeleteAllSelectedExecutionResults(object sender, System.Windows.RoutedEventArgs e)
        {
            if ((Reporter.ToUser(eUserMsgKey.AllExecutionsResultsToDelete)) == Amdocs.Ginger.Common.eUserMsgSelection.Yes)
            {
                foreach (RunSetReport runSetReport in grdExecutionsHistory.Grid.Items)
                {
                    string runSetFolder = executionLoggerHelper.GetLoggerDirectory(runSetReport.LogFolder);

                    var fi = new DirectoryInfo(runSetFolder);
                    CleanDirectory(fi.FullName);
                    fi.Delete();
                }

                if (grdExecutionsHistory.Grid.SelectedItems.Count > 0)
                {
                    LoadExecutionsHistoryData();
                }
            }
        }

19 Source : Images.cs
with GNU General Public License v3.0
from Guerra24

public Task Init()
		{
			return Task.Run(() =>
			{
				try
				{
					imagesCache.Clear();
					imagesSizeCache.Clear();
					thumbnailsCache.Clear();
					var files = thumbnailCacheDirectory.GetFiles("*.*", SearchOption.AllDirectories);
					files.Where(file => file.CreationTime < DateTime.Now.AddDays(-14)).ToList().ForEach(file => file.Delete());
					var directories = thumbnailCacheDirectory.GetDirectories();
					directories.Where(dir => dir.GetFiles().Length == 0).ToList().ForEach(dir => dir.Delete());
				}
				catch (Exception e)
				{
					Crashes.TrackError(e);
				}
			});
		}

19 Source : Program.cs
with MIT License
from IllusionMods

private static Results CleanTranslations(DirectoryInfo dir, DirectoryInfo rootDir)
        {
            var files = dir.GetFiles("*.txt", SearchOption.TopDirectoryOnly);
            var folders = dir.GetDirectories();

            var folderPercentage = new Results();

            foreach (var file in files)
            {
                if (file.Name == "_AutoGeneratedTranslations.txt")
                {
                    file.Delete();
                    continue;
                }

                var lines = File.ReadAllLines(file.FullName).Where(x => !string.IsNullOrWhiteSpace(x)).ToArray();
                var notComments = lines.Where(x => !x.StartsWith("//")).ToArray();

                try
                {
                    file.Delete();

                    if (notComments.Length != 0)
                        File.WriteAllLines(file.FullName, notComments);
                }
                catch (Exception e)
                {
                    Console.ForegroundColor = ConsoleColor.Red;
                    _originalOut.WriteLine(e.Message);
                }

                //var percentage = (float)translatedLines.Length / (float)lines.Length;
                //Console.ForegroundColor = ConsoleColor.DarkGray;
                //Console.WriteLine($"{file.FullName} - {translatedLines.Length}/{lines.Length} lines - {100 * percentage:F0}%");

                // Don't count MTL
                if (file.Name != "zz_machineTranslation.txt")
                {
                    folderPercentage.Total += lines.Count(x => x.Contains('=') && !x.EndsWith("=---"));
                    folderPercentage.Translated += lines.Count(x => x.Contains('=') && !x.StartsWith("//") && !x.EndsWith("=---"));
                }
            }

            foreach (var folder in folders)
            {
                var r = CleanTranslations(folder, rootDir);
                folderPercentage.Add(r);
            }

            Console.ForegroundColor = ConsoleColor.White;
            Console.WriteLine($"{dir.FullName.Remove(0, rootDir.FullName.Length)} - {folderPercentage.Translated}/{folderPercentage.Total} lines - {100 * folderPercentage.GetPercent():F1}%");

            if (dir.GetFiles("*", SearchOption.AllDirectories).Length == 0)
            {
                try
                {
                    dir.Delete();
                }
                catch (Exception e)
                {
                    Console.ForegroundColor = ConsoleColor.Red;
                    _originalOut.WriteLine(e.Message);
                }
            }

            return folderPercentage;
        }

19 Source : AutoTx.cs
with GNU General Public License v3.0
from imcf

private void ProcessQueuedDirectories() {
            // only proceed when in a valid state:
            if (_transferState != TxState.Stopped)
                return;

            // check the "processing" location for directories:
            var queued = new DirectoryInfo(_config.ProcessingPath).GetDirectories();
            if (queued.Length == 0)
                return;

            var subdirs = queued[0].GetDirectories();
            // having no subdirectories should not happen in theory - in practice it could e.g. if
            // an admin is moving around stuff while the service is operating, so better be safe:
            if (subdirs.Length == 0) {
                Log.Warn("WARNING: empty processing directory found: {0}", queued[0].Name);
                try {
                    queued[0].Delete();
                    Log.Debug("Removed empty directory: {0}", queued[0].Name);
                }
                catch (Exception ex) {
                    Log.Error("Error deleting directory: {0} - {1}", queued[0].Name, ex.Message);
                }
                return;
            }

            // give the system some time before starting the next transfer:
            if (_waitCyclesBeforeNextTx > 0) {
                Log.Debug("Waiting {0} more cycles before starting the next transfer...",
                    _waitCyclesBeforeNextTx);
                return;
            }

            // dispatch the next directory from "processing" for transfer:
            try {
                StartTransfer(subdirs[0].FullName);
            }
            catch (Exception ex) {
                Log.Error("Error checking for data to be transferred: {0}", ex.Message);
                throw;
            }
        }

19 Source : AutoTx.cs
with GNU General Public License v3.0
from imcf

private void MoveToGraceLocation() {
            string errMsg;
            // CurrentTransferSrc is e.g. D:\ATX\PROCESSING\2017-04-02__12-34-56\user00
            var sourceDirectory = new DirectoryInfo(_status.CurrentTransferSrc);
            var dstPath = Path.Combine(
                _config.DonePath,
                sourceDirectory.Name, // the username directory
                TimeUtils.Timestamp());
            Log.Trace("MoveToGraceLocation: src({0}) dst({1})", sourceDirectory.FullName, dstPath);

            try {
                if (FsUtils.MoveAllSubDirs(sourceDirectory, dstPath)) {
                    // clean up the processing location:
                    sourceDirectory.Delete();
                    if (sourceDirectory.Parent != null)
                        sourceDirectory.Parent.Delete();
                    // check age and size of existing folders in the grace location after
                    // a transfer has completed, trigger a notification if necessary:
                    Log.Debug(SendGraceLocationSummary(_config.GracePeriod));
                    return;
                }
                errMsg = "unable to move " + sourceDirectory.FullName;
            }
            catch (Exception ex) {
                errMsg = ex.Message;
            }
            Log.Error("MoveToGraceLocation() failed: {0}", errMsg);
        }

19 Source : BundleUtil.cs
with MIT License
from iothua

private static void DeleteEmptyDirectory(DirectoryInfo directory)
        {
            try
            {
                if (directory.GetFiles().Length > 0)
                    return;

                DirectoryInfo[] arr = directory.GetDirectories();
                foreach (DirectoryInfo dir in arr)
                {
                    DeleteEmptyDirectory(dir);
                }

                arr = directory.GetDirectories();
                if (arr.Length <= 0)
                {
                    directory.Delete();
                    return;
                }
            }
            catch (Exception)
            {
            }
        }

19 Source : DirectoryUtil.cs
with MIT License
from jianxuanbing

public static bool Delete(string directory, bool isDeleteRoot = true)
        {
            directory.CheckNotNullOrEmpty(nameof(directory));

            bool flag = false;
            DirectoryInfo dirPathInfo = new DirectoryInfo(directory);
            if (dirPathInfo.Exists)
            {
                //删除目录下所有文件
                foreach (FileInfo fileInfo in dirPathInfo.GetFiles())
                {
                    fileInfo.Delete();
                }
                //递归删除所有子目录
                foreach (DirectoryInfo subDirectory in dirPathInfo.GetDirectories())
                {
                    Delete(subDirectory.FullName);
                }
                //删除目录
                if (isDeleteRoot)
                {
                    dirPathInfo.Attributes = FileAttributes.Normal;
                    dirPathInfo.Delete();
                }
                flag = true;
            }
            return flag;
        }

19 Source : ClassLoger.cs
with Apache License 2.0
from liemei

void Worker()
        {
            string logpath = ClreplacedLoger.LogPath;
            int time = 0;
            while (iswork)
            {
                Thread.Sleep(1000);
                time++;
                if (time < 60 * 60)
                    continue;
                time = 0;
                while (!Directory.Exists(logpath))
                {
                    Thread.Sleep(3000);
                }
                try
                {
                    System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(logpath);

                    System.IO.DirectoryInfo[] childsdir = di.GetDirectories(); ;

                    foreach (DirectoryInfo d in childsdir)
                    {
                        try
                        {
                            string dirname = d.Name;
                            DateTime now = DateTime.Now;
                            if (dirname.Length == 6 || dirname.Length == 5)
                            {
                                string yeay_str = dirname.Substring(0, 4);
                                string month_str = dirname.Substring(4);
                                int year = 0;
                                int month = 0;
                                if (!int.TryParse(yeay_str, out year) || !int.TryParse(month_str, out month))
                                {
                                    try
                                    {
                                        d.Delete(true);
                                    }
                                    catch
                                    { }
                                    continue;
                                }

                                //删除上月日志
                                if (year < now.Year || month + 2 < now.Month)
                                {
                                    try
                                    {
                                        d.Delete(true);
                                        continue;
                                    }
                                    catch
                                    { }

                                }
                                if (year == now.Year && month <= now.Month)
                                {
                                    FileInfo[] fis = d.GetFiles();
                                    foreach (FileInfo f in fis)
                                    {
                                        try
                                        {
                                            int day = 0;
                                            string day_str = f.Name.Replace(f.Extension, "");
                                            if (int.TryParse(day_str, out day))
                                            {
                                                DateTime ftime = new DateTime(year, month, day);
                                                if (((TimeSpan)(now - ftime)).TotalDays > 15)
                                                {
                                                    f.Delete();
                                                }
                                            }
                                            else
                                            {
                                                f.Delete();
                                            }
                                        }
                                        catch
                                        { }
                                    }
                                }
                            }
                            else
                            {
                                try
                                {
                                    d.Delete();
                                }
                                catch
                                { }
                            }
                        }
                        catch
                        { }
                    }
                }
                catch
                { }
            }
        }

19 Source : DirectoryUtil.cs
with MIT License
from lysilver

public static bool Delete(string directory, bool isDeleteRoot = true)
        {
            CheckNull.ArgumentIsNullException(directory, nameof(directory));
            var flag = false;
            var dirPathInfo = new DirectoryInfo(directory);
            if (dirPathInfo.Exists)
            {
                //删除目录下所有文件
                foreach (var fileInfo in dirPathInfo.GetFiles())
                {
                    fileInfo.Delete();
                }
                //递归删除所有子目录
                foreach (var subDirectory in dirPathInfo.GetDirectories())
                {
                    Delete(subDirectory.FullName);
                }
                //删除目录
                if (isDeleteRoot)
                {
                    dirPathInfo.Attributes = FileAttributes.Normal;
                    dirPathInfo.Delete();
                }
                flag = true;
            }
            return flag;
        }

19 Source : Program.cs
with GNU General Public License v3.0
from maxsnts

static void Main(string[] args)
        {
            try
            {

                Updating upd = new Updating();
                upd.Show();
                upd.Update();

                if (args.Length == 3)
                {
                    string runprocess = args[0];
                    string zipfile = args[1];
                    string destination = args[2];

                    //wait a bit
                    Thread.Sleep(500);

                    //kill running process if its still there
                    foreach (var process in Process.GetProcessesByName(runprocess.Replace(".exe", "")))
                        process.Kill();

                    //wait another bit
                    Thread.Sleep(500);

                    if (!File.Exists(zipfile))
                        return;

                    try
                    {
                        //try delete every file except config
                        DirectoryInfo dir = new DirectoryInfo(destination);
                        foreach (var item in dir.EnumerateFiles("*.*", SearchOption.AllDirectories))
                        {
                            if (item.Name.StartsWith("#"))
                                continue;

                            if (item.Name.ToLower() == zipfile.ToLower())
                                continue;

                            if (item.Name.ToLower() == "xwupdater.exe")
                                continue;

                            item.Delete();
                        }

                        foreach (var item in dir.EnumerateDirectories("*.*", SearchOption.AllDirectories))
                        {
                            item.Delete();
                        }
                    }
                    catch
                    { /* maybe its not a problem to ignore this */ }

                    //unzip new
                    using (ZipArchive archive = ZipFile.Open(zipfile, ZipArchiveMode.Read))
                    {
                        foreach (ZipArchiveEntry file in archive.Entries)
                        {
                            string completeFileName = Path.Combine(destination, file.FullName);
                            if (file.Name == "")
                            {// replaceduming Empty for Directory
                                Directory.CreateDirectory(Path.GetDirectoryName(completeFileName));
                                continue;
                            }
                            // create dirs
                            var dirToCreate = destination;
                            for (var i = 0; i < file.FullName.Split('/').Length - 1; i++)
                            {
                                var s = file.FullName.Split('/')[i];
                                dirToCreate = Path.Combine(dirToCreate, s);
                                if (!Directory.Exists(dirToCreate))
                                    Directory.CreateDirectory(dirToCreate);
                            }
                            file.ExtractToFile(completeFileName, true);
                        }
                    }
                    
                    //run process again
                    using (Process process = new Process())
                    {
                        process.StartInfo.FileName = runprocess;
                        process.StartInfo.Arguments = "";
                        process.StartInfo.WindowStyle = ProcessWindowStyle.Normal;
                        process.Start();
                    }

                    //delete zip
                    File.Delete(zipfile);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"Unable to update. Please download and update manually\n\n{ex.Message}");
            }
        }

19 Source : DirectoryInfoProxy.cs
with Apache License 2.0
from microsoft

public void Delete() => _directoryInfo.Delete();

19 Source : SystemIORunner.cs
with MIT License
from microsoft

public override string DeleteDirectory(string path)
        {
            DirectoryInfo directory = new DirectoryInfo(path);

            foreach (FileInfo file in directory.GetFiles())
            {
                file.Attributes = FileAttributes.Normal;

                RetryOnException(() => file.Delete());
            }

            foreach (DirectoryInfo subDirectory in directory.GetDirectories())
            {
                this.DeleteDirectory(subDirectory.FullName);
            }

            RetryOnException(() => directory.Delete());
            return string.Empty;
        }

19 Source : PhysicalFileSystem.cs
with MIT License
from microsoft

public virtual void DeleteDirectory(string path, bool recursive = true, bool ignoreDirectoryDeleteExceptions = false)
        {
            if (!Directory.Exists(path))
            {
                return;
            }

            DirectoryInfo directory = new DirectoryInfo(path);

            if (recursive)
            {
                foreach (FileInfo file in directory.GetFiles())
                {
                    file.Attributes = FileAttributes.Normal;
                    file.Delete();
                }

                foreach (DirectoryInfo subDirectory in directory.GetDirectories())
                {
                    this.DeleteDirectory(subDirectory.FullName, recursive, ignoreDirectoryDeleteExceptions);
                }
            }

            try
            {
                directory.Delete();
            }
            catch (Exception)
            {
                if (!ignoreDirectoryDeleteExceptions)
                {
                    throw;
                }
            }
        }

19 Source : JunctionAndSubstTests.cs
with MIT License
from microsoft

[TearDown]
        public void TearDownJunctionRoot()
        {
            DirectoryInfo junctionsRootInfo = new DirectoryInfo(this.junctionsRoot);
            if (junctionsRootInfo.Exists)
            {
                foreach (DirectoryInfo junction in junctionsRootInfo.GetDirectories())
                {
                    junction.Delete();
                }

                junctionsRootInfo.Delete();
            }
        }

19 Source : CacheManageSvc.cs
with GNU Affero General Public License v3.0
from Milkitic

private static void ClearCache(string path)
        {
            var folder = new DirectoryInfo(path);
            var files = folder.EnumerateFiles();
            foreach (var file in files)
            {
                try
                {
                    if (DateTime.Now - file.CreationTime > new TimeSpan(0, 30, 0))
                        file.Delete();
                }
                catch (Exception ex)
                {
                    Logger.Exception(ex);
                }
            }

            var folders = folder.EnumerateDirectories();
            foreach (var f in folders)
            {
                ClearCache(f.FullName);
                try
                {
                    if (DateTime.Now - f.CreationTime > new TimeSpan(0, 30, 0))
                        f.Delete();
                }
                catch (Exception ex)
                {
                    Logger.Exception(ex);
                }
            }
        }

19 Source : IOExtensions.cs
with GNU General Public License v3.0
from Mo-Ink

public static void MoveTo(this DirectoryInfo directory, string destDirName, bool overwrite)
        {
            if (!Directory.Exists(destDirName))
            {
                Directory.CreateDirectory(destDirName);
            }

            foreach (var fileSystemInfo in directory.GetFileSystemInfos())
            {
                fileSystemInfo.MoveTo(Path.Combine(destDirName, fileSystemInfo.Name), overwrite);
            }

            if (!directory.GetFileSystemInfos().Any())
            {
                directory.Delete();
            }
        }

19 Source : Util.cs
with MIT License
from mob-sakai

[InitializeOnLoadMethod]
		public static void RevertExcludedDirectory () {
			DirectoryInfo exDir = new DirectoryInfo (EXCLUDE_BUILD_DIR);
			if (!exDir.Exists)
				return;

			foreach (DirectoryInfo d in exDir.GetDirectories()) 
				MoveDirectory (d.FullName, d.Name.Replace ("~~", "/"));

			foreach (FileInfo f in exDir.GetFiles())
				f.Delete (); 

			exDir.Delete ();
			replacedetDatabase.Refresh();
		}

19 Source : LuceneIndexen.cs
with MIT License
from nelemans1971

private void ClearAndRemoveFolder(string folderName)
        {
            if (string.IsNullOrEmpty(folderName) || folderName.Trim().Length <= 3)
            {
                return;
            }

            int retryCount = 3;
            try
            {
                DirectoryInfo dir = new DirectoryInfo(folderName);
                foreach (FileInfo fi in dir.GetFiles())
                {
                    retryCount = 3;
                    while (retryCount > 0)
                    {
                        try
                        {
                            fi.IsReadOnly = false;
                            fi.Delete();
                            retryCount = 0;
                        }
                        catch
                        {
                            GC.WaitForPendingFinalizers();
                            retryCount--;
                        }
                    } //while
                }

                foreach (DirectoryInfo di in dir.GetDirectories())
                {
                    ClearAndRemoveFolder(di.FullName);
                    di.Delete();
                }

                retryCount = 3;
                while (retryCount > 0)
                {
                    try
                    {
                        System.IO.Directory.Delete(folderName);
                    }
                    catch
                    {
                        GC.WaitForPendingFinalizers();
                        retryCount--;
                    }
                } //while
            }
            catch
            {
            }
        }

19 Source : ReceiveIndex.cs
with MIT License
from nelemans1971

private void ClearAndRemoveFolder(string folderName)
        {
            if (string.IsNullOrEmpty(folderName) || folderName.Trim().Length <= 3)
            {
                return;
            }

            try
            {
                DirectoryInfo dir = new DirectoryInfo(folderName);
                foreach (FileInfo fi in dir.GetFiles())
                {
                    fi.IsReadOnly = false;
                    fi.Delete();
                }

                foreach (DirectoryInfo di in dir.GetDirectories())
                {
                    ClearAndRemoveFolder(di.FullName);
                    di.Delete();
                }

                Directory.Delete(folderName);
            }
            catch
            {
            }
        }

19 Source : Worker.cs
with MIT License
from nelemans1971

private void ClearFolder(string folderName)
        {
            DirectoryInfo dir = new DirectoryInfo(folderName);

            foreach (FileInfo fi in dir.GetFiles())
            {
                fi.IsReadOnly = false;
                fi.Delete();
            } //foreach

            foreach (DirectoryInfo di in dir.GetDirectories())
            {
                ClearFolder(di.FullName);
                di.Delete();
            } //foreach
        }

19 Source : Uninstall.cs
with GNU General Public License v3.0
from OpenByteDev

public static void Run(bool deleteSettings = false) {
            Autostart.Disable();
            StartWithSpotify.Disable();

            if (deleteSettings) {
                App.SaveSettingsOnClose = false;
                DeleteSettings();
            }

            Process.Start(new ProcessStartInfo() {
                FileName = "cmd.exe",
                Arguments = "/C choice /C Y /N /D Y /T 5 & DEL " + App.Location,
                WindowStyle = ProcessWindowStyle.Hidden,
                CreateNoWindow = true,
            });

            Application.Current?.Dispatcher.Invoke(() => Application.Current.Shutdown());

            void DeleteSettings() {
                var appExecutableName = Path.GetFileName(App.Location);
                var appDataPath = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
                var containerPath = Path.Combine(appDataPath, App.CompanyName);
                var containerDiretory = new DirectoryInfo(containerPath);

                var settingsDirectories = containerDiretory.GetDirectories()
                    .Where(directory => directory.Name.StartsWith(appExecutableName));

                foreach (var settingsDir in settingsDirectories)
                    settingsDir.RecursiveDelete();

                if (!containerDiretory.EnumerateDirectories().Any() && !containerDiretory.EnumerateFiles().Any())
                    containerDiretory.Delete();
            }
        }

19 Source : Installer.cs
with GNU General Public License v3.0
from OpenTabletDriver

public async Task<bool> Install()
        {
            if (await Downloader.CheckIfCanDownload())
            {
                CleanDirectory(InstallationDirectory);

                var repo = await Downloader.GetRepository(GitHubInfo.MainRepository);
                var release = await Downloader.GetLatestRelease(repo);
                var replacedet = await Downloader.GetCurrentPlatformreplacedet(repo, release);
                var extension = replacedet.Name.Split('.').Last();
                
                using (var httpStream = await Downloader.GetreplacedetStream(replacedet))
                {
                    if (extension == "zip")
                    {
                        // Create a temporary file to extract from
                        var filename = $"{Guid.NewGuid()}.zip";
                        var file = new FileInfo(Path.Join(TempDirectory.FullName, filename));
                        using (var fileStream = file.Create())
                            await CopyStreamWithProgress(replacedet.Size, httpStream, fileStream);

                        // Extract to directory
                        ZipFile.ExtractToDirectory(file.FullName, InstallationDirectory.FullName);
                        // Clean up files
                        file.Delete();
                    }
                    else if (extension == "gz")
                    {
                        using (var memoryStream = new MemoryStream(replacedet.Size))
                        {
                            await CopyStreamWithProgress(replacedet.Size, httpStream, memoryStream);
                            using (var decompressionStream = new GZipStream(memoryStream, CompressionMode.Decompress))
                            using (var tar = TarArchive.CreateInputTarArchive(decompressionStream))
                            {    
                                // Extract to directory
                                tar.ExtractContents(InstallationDirectory.FullName);
                            }
                        }

                        // Extraction can create a duplicate root directory, so we move everything out and delete the duplicate root.
                        var children = InstallationDirectory.GetDirectories();
                        if (!children.Any(d => d.Name == "Configurations") && children.Count() == 1)
                        {
                            var parent = children.First();
                            foreach (var fsinfo in parent.GetFileSystemInfos())
                            {
                                if (fsinfo is FileInfo file)
                                    file.MoveTo(Path.Join(InstallationDirectory.FullName, file.Name));
                                else if (fsinfo is DirectoryInfo dir)
                                    dir.MoveTo(Path.Join(InstallationDirectory.FullName, dir.Name));
                            }
                            parent.Delete();
                        }

                        var executables = from file in InstallationDirectory.EnumerateFiles()
                            where file.Name == Launcher.AppName || file.Name == Launcher.DaemonName || file.Name == Launcher.ConsoleName
                            select file;

                        // Set file permissions on Unix platforms
                        foreach (var file in executables)
                        {
                            switch (SystemInfo.CurrentPlatform)
                            {
                                case RuntimePlatform.Linux:
                                case RuntimePlatform.MacOS:
                                case RuntimePlatform.FreeBSD:
                                    Process.Start("chmod", $"+rwx \"{file.FullName}\"");
                                    break;
                            }
                        }
                    }
                    else
                    {
                        throw new Exception("Unknown file extension, unable to decompress.");
                    }
                }

                var versionInfo = new VersionInfo(release.TagName);
                using (var fs = VersionInfoFile.OpenWrite())
                    versionInfo.Serialize(fs);

                return true;
            }
            return false;
        }

See More Examples