C# Directory.Delete的代码示例

Directory.Delete方法的主要功能描述

通过代码示例来学习C# Directory.Delete方法

通过代码示例来学习编程是非常高效的。
1. 代码示例提供了一个具体而直观的学习环境,使初学者能够立即看到编程概念和语法的实际应用。
2. 通过分析和模仿现有的代码实例,初学者可以更好地理解编程逻辑和算法的工作原理。
3. 代码实例往往涵盖了多种编程技巧和最佳实践,通过学习和模仿这些实例,学习者可以逐步掌握如何编写高效、可读性强和可维护的代码。这对于初学者来说,是一种快速提升编程水平的有效途径。


Directory.Delete是C#的System.IO命名空间下中的一个方法, 小编为大家找了一些网络大拿们常见的代码示例,源码中的Directory.Delete() 已经帮大家高亮显示了,大家可以重点学习Directory.Delete() 方法的写法,从而快速掌握该方法的应用。

Directory.Delete的代码示例1 - NewFolderAttributesAreUpdated()

    using System.IO;

        [TestCaseSource(typeof(FileRunnersAndFolders), nameof(FileRunnersAndFolders.Folders))]
        public void NewFolderAttributesAreUpdated(string parentFolder)
        {
            string folderName = Path.Combine(parentFolder, "FolderAttributesAreUpdated");
            string virtualFolder = this.Enlistment.GetVirtualPathTo(folderName);
            Directory.CreateDirectory(virtualFolder);

            FileSystemRunner fileSystem = FileSystemRunner.DefaultRunner;

            virtualFolder.ShouldBeADirectory(fileSystem);

            // Update defaults. DirectoryInfo is not batched, so each of these will create a separate Open-Update-Close set.
            DirectoryInfo before = new DirectoryInfo(virtualFolder);
            DateTime testValue = DateTime.Now + TimeSpan.FromDays(1);
            before.CreationTime = testValue;
            before.LastAccessTime = testValue;
            before.LastWriteTime = testValue;
            before.Attributes = FileAttributes.Hidden;

            // DirectoryInfo caches information. We can refresh, but just to be absolutely sure...
            virtualFolder.ShouldBeADirectory(fileSystem)
                .WithInfo(testValue, testValue, testValue, FileAttributes.Hidden | FileAttributes.Directory, ignoreRecallAttributes: false);

            Directory.Delete(virtualFolder);
        }
    

开发者ID: microsoft,   项目名称: VFSForGit,   代码行数: 27,   代码来源: BasicFileSystemTests.cs

在microsoft提供的NewFolderAttributesAreUpdated()方法中,该源代码示例一共有27行, 其中使用了Directory.Delete()1次, 并且小编将这些方法高亮显示出来了,希望对您了解Directory.Delete()有帮助。 如果您觉得有帮助的话,请帮忙点赞或转发。
该代码示例的点赞次数为3, 点赞数越大, 从某种程度说明这个示例对了解Directory.Delete()可能更有帮助。

Directory.Delete的代码示例2 - HandleAllDirectoryOperations()

    using System.IO;

        private void HandleAllDirectoryOperations()
        {
            DiffTreeResult treeOp;
            while (this.diff.DirectoryOperations.TryDequeue(out treeOp))
            {
                string absoluteTargetPath = Path.Combine(this.enlistment.WorkingDirectoryBackingRoot, treeOp.TargetPath);

                if (this.HasFailures)
                {
                    return;
                }

                switch (treeOp.Operation)
                {
                    case DiffTreeResult.Operations.Modify:
                    case DiffTreeResult.Operations.Add:
                        try
                        {
                            Directory.CreateDirectory(absoluteTargetPath);
                        }
                        catch (Exception ex)
                        {
                            EventMetadata metadata = new EventMetadata();
                            metadata.Add("Operation", "CreateDirectory");
                            metadata.Add(nameof(treeOp.TargetPath), absoluteTargetPath);
                            this.tracer.RelatedError(metadata, ex.Message);
                            this.HasFailures = true;
                        }

                        break;
                    case DiffTreeResult.Operations.Delete:
                        try
                        {
                            if (Directory.Exists(absoluteTargetPath))
                            {
                                this.fileSystem.DeleteDirectory(absoluteTargetPath);
                            }
                        }
                        catch (Exception ex)
                        {
                            // We are deleting directories and subdirectories in parallel
                            if (Directory.Exists(absoluteTargetPath))
                            {
                                EventMetadata metadata = new EventMetadata();
                                metadata.Add("Operation", "DeleteDirectory");
                                metadata.Add(nameof(treeOp.TargetPath), absoluteTargetPath);
                                this.tracer.RelatedError(metadata, ex.Message);
                                this.HasFailures = true;
                            }
                        }

                        break;
                    default:
                        this.tracer.RelatedError("Ignoring unexpected Tree Operation {0}: {1}", absoluteTargetPath, treeOp.Operation);
                        continue;
                }

                if (Interlocked.Increment(ref this.directoryOpCount) % NumOperationsPerStatus == 0)
                {
                    EventMetadata metadata = new EventMetadata();
                    metadata.Add("DirectoryOperationsQueued", this.diff.DirectoryOperations.Count);
                    metadata.Add("DirectoryOperationsCompleted", this.directoryOpCount);
                    this.tracer.RelatedEvent(EventLevel.Informational, "CheckoutStatus", metadata);
                }
            }
        }
    

开发者ID: microsoft,   项目名称: VFSForGit,   代码行数: 68,   代码来源: CheckoutStage.cs

在microsoft提供的HandleAllDirectoryOperations()方法中,该源代码示例一共有68行, 其中使用了Directory.Delete()1次, 并且小编将这些方法高亮显示出来了,希望对您了解Directory.Delete()有帮助。 如果您觉得有帮助的话,请帮忙点赞或转发。
该代码示例的点赞次数为3, 点赞数越大, 从某种程度说明这个示例对了解Directory.Delete()可能更有帮助。

Directory.Delete的代码示例3 - SetDirectoryLastWriteTime()

    using System.IO;

        public static void SetDirectoryLastWriteTime(string path, DateTime lastWriteTime, out bool directoryExists)
        {
            // We can't use Directory.SetLastWriteTime as it requests GENERIC_WRITE access
            // which will fail for directory placeholders.  The only access requried by SetFileTime
            // is FILE_WRITE_ATTRIBUTES (which ProjFS does allow for placeholders)

            using (SafeFileHandle handle =
                CreateFile(
                    path,
                    FileAccess.FILE_WRITE_ATTRIBUTES,
                    FileShare.ReadWrite | FileShare.Delete,
                    IntPtr.Zero,
                    FileMode.Open,
                    FileAttributes.FILE_FLAG_BACKUP_SEMANTICS,
                    IntPtr.Zero))
            {
                if (handle.IsInvalid)
                {
                    int error = Marshal.GetLastWin32Error();
                    if (error == ERROR_FILE_NOT_FOUND || error == ERROR_PATH_NOT_FOUND)
                    {
                        directoryExists = false;
                        return;
                    }

                    throw new Win32Exception(error, $"{nameof(SetDirectoryLastWriteTime)}: Failed to open handle for '{path}'");
                }

                // SetFileTime will not update times with value 0
                long creationFileTime = 0;
                long lastAccessFileTime = 0;
                long lastWriteFileTime = lastWriteTime.ToFileTime();
                if (!SetFileTime(handle, ref creationFileTime, ref lastAccessFileTime, ref lastWriteFileTime))
                {
                    ThrowLastWin32Exception($"{nameof(SetDirectoryLastWriteTime)}: Failed to update last write time for '{path}'");
                }
            }

            directoryExists = true;
            return;
        }
    

开发者ID: microsoft,   项目名称: VFSForGit,   代码行数: 43,   代码来源: NativeMethods.cs

在microsoft提供的SetDirectoryLastWriteTime()方法中,该源代码示例一共有43行, 其中使用了Directory.Delete()1次, 并且小编将这些方法高亮显示出来了,希望对您了解Directory.Delete()有帮助。 如果您觉得有帮助的话,请帮忙点赞或转发。
该代码示例的点赞次数为3, 点赞数越大, 从某种程度说明这个示例对了解Directory.Delete()可能更有帮助。

Directory.Delete的代码示例4 - DeleteDirectory()

    using System.IO;

        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;
                }
            }
        }
    

开发者ID: microsoft,   项目名称: VFSForGit,   代码行数: 37,   代码来源: PhysicalFileSystem.cs

在microsoft提供的DeleteDirectory()方法中,该源代码示例一共有37行, 其中使用了Directory.Delete()2次, 并且小编将这些方法高亮显示出来了,希望对您了解Directory.Delete()有帮助。 如果您觉得有帮助的话,请帮忙点赞或转发。
该代码示例的点赞次数为3, 点赞数越大, 从某种程度说明这个示例对了解Directory.Delete()可能更有帮助。

Directory.Delete的代码示例5 - DeleteIfExists()

    using System.IO;

        /// 
        /// Deletes File/Directory from by the specified path if it exists.
        /// 
        /// The path.
        /// if set to false handle all exceptions silently.
        /// 
        public static string DeleteIfExists(this string path, bool @throw = false)
        {
            void deleteFile(string file)
            {
                try
                {
                    var fullPath = IO.Path.GetFullPath(file);
                    if (IO.File.Exists(fullPath))
                        IO.File.Delete(fullPath);
                }
                catch
                {
                    if (@throw)
                        throw;
                }
            }

            void deleteDir(string file)
            {
                try
                {
                    var fullPath = IO.Path.GetFullPath(file);
                    if (IO.Directory.Exists(fullPath))
                        IO.Directory.Delete(fullPath);
                }
                catch
                {
                    if (@throw)
                        throw;
                }
            }

            if (path.IsDirectory())
            {
                IO.Directory.GetFiles(path, "*", IO.SearchOption.AllDirectories)
                            .ForEach(deleteFile);

                IO.Directory.GetDirectories(path, "*", IO.SearchOption.AllDirectories)
                            .OrderByDescending(x => x)
                            .ForEach(deleteDir);

                deleteDir(path);
            }
            else
            {
                deleteFile(path);
            }

            return path;
        }
    

开发者ID: oleg-shilo,   项目名称: wixsharp,   代码行数: 58,   代码来源: Extensions.cs

在oleg-shilo提供的DeleteIfExists()方法中,该源代码示例一共有58行, 其中使用了Directory.Delete()2次, 并且小编将这些方法高亮显示出来了,希望对您了解Directory.Delete()有帮助。 如果您觉得有帮助的话,请帮忙点赞或转发。
该代码示例的点赞次数为3, 点赞数越大, 从某种程度说明这个示例对了解Directory.Delete()可能更有帮助。

Directory.Delete的代码示例6 - CanBuildAllSamples()

    using System.IO;

        [Fact]
        public void CanBuildAllSamples()
        {
            // if (Environment.GetEnvironmentVariable("APPVEYOR") != null)
            //     return;

            // need to exclude some samples; for example the two samples from the same dir will interfere with each other;
            // or some other tests are built as a part of the solution
            string[] exclude = new string[] { };

            var failedSamples = new List();
            int startStep = 0;
            int? howManyToRun = null; //null - all
            int? whichOneToRun = null; //null - all
            int sampleDirIndex = 0;

            var files = Directory.GetFiles(@"..\..\..\WixSharp.Samples\Wix# Samples", "build*.cmd", SearchOption.AllDirectories);
            var compiled_scripts = Directory.GetFiles(@"..\..\..\WixSharp.Samples\Wix# Samples", "setup*.cs.dll", SearchOption.AllDirectories);

            compiled_scripts.ForEach(x => System.IO.File.Delete(x));

            files = files.Where(f => !exclude.Any(y => f.EndsWith(y, ignoreCase: true))).ToArray();

            files = files.Skip(startStep).ToArray();

            if (whichOneToRun.HasValue)
                files = new[] { files[whichOneToRun.Value] };

            if (howManyToRun.HasValue)
                files = files.Take(howManyToRun.Value).ToArray();

            samplesTotal = files.Count();
            testTime.Reset();
            testTime.Start();

            var samples = files.GroupBy(x => Path.GetDirectoryName(x));

            var allSamples = samples.Select(g => new { Category = g.Key, Items = g, Index = ++sampleDirIndex }).ToArray();

            var parallel = false;

#if DEBUG
            parallel = true;
            ShowLogFileToObserveProgress();
            // System.Diagnostics.Process.GetProcessesByName("cmd").ToList().ForEach(x => { try { x.Kill(); } catch { } });
            // System.Diagnostics.Process.GetProcessesByName("cscs").ToList().ForEach(x => { try { x.Kill(); } catch { } });
            // System.Diagnostics.Process.GetProcessesByName("conhost").ToList().ForEach(x => { try { x.Kill(); } catch { } });
#endif

            void processDir(dynamic group)
            {
                string sampleDir = group.Category;

                var sampleFiles = Directory.GetFiles(sampleDir, "build*.cmd")
                                           .Select(x => Path.GetFullPath(x))
                                           .ToArray();

                foreach (string batchFile in sampleFiles)
                {
                    BuildSample(batchFile, group.Index, failedSamples);
                }
            };

            if (parallel)
            {
                // allSamples.ForEach(item =>
                //     ThreadPool.QueueUserWorkItem(x =>
                //         processDir(item)));

                Parallel.ForEach(allSamples, processDir);
                while (completedSamples < samplesTotal)
                {
                    Thread.Sleep(1000);
                }
            }
            else
            {
                foreach (var item in allSamples)
                    processDir(item);
            }

            testTime.Stop();
            LogAppend("\r\n--- END ---");

            if (failedSamples.Any())
            {
                string error = " Completed Samples: " + completedSamples + "\r\n Failed Samples:\r\n" + string.Join(Environment.NewLine, failedSamples.ToArray());
                Assert.True(false, error);
            }
        }
    

开发者ID: oleg-shilo,   项目名称: wixsharp,   代码行数: 92,   代码来源: SamplesTest.cs

在oleg-shilo提供的CanBuildAllSamples()方法中,该源代码示例一共有92行, 其中使用了Directory.Delete()1次, 并且小编将这些方法高亮显示出来了,希望对您了解Directory.Delete()有帮助。 如果您觉得有帮助的话,请帮忙点赞或转发。
该代码示例的点赞次数为3, 点赞数越大, 从某种程度说明这个示例对了解Directory.Delete()可能更有帮助。

Directory.Delete()方法的常见问题及解答

C#中Directory.Delete()的常见错误类型及注意事项

Directory.Delete的错误类型有很多, 这里就不一一阐述了,本文只列出一些常见的代码示例供参考,大家可以看一下代码中Catch语句中是否有常见的错误捕获及处理。

C#中Directory.Delete()的构造函数有哪些

Directory.Delete构造函数功能基本类似,只是参数不同; 目前主流的集成开发环境都已经带智能提醒了,如:Visual Studio; 大家可以非常轻松的通过Visual Studio中的智能提醒,了解对应构造函数的用法。

如何使用ChartGPT写一段Directory.Delete的代码

你可以在ChartGPT中输入如下的指令:"提供一个如何使用Directory.Delete的C#代码示例"
ChartGPT写出的代码和本文中的小编提供的代码的区别。 ChartGPT发展到现在已经非常聪明了,但需要使用这提供非常专业的问题,才可能有比较好的源代码示例; 而本文中, 小编已经帮您列出来基本所有类和所有方法的使用示例, 而且这些示例基本都是一些网络大佬提供的源码,可以更方便的供一些开发菜鸟或者资深开发参考和学习。

Directory.Delete所在的类及名称空间

Directory.Delete是System.IO下的方法。

Directory.Delete怎么使用?

Directory.Delete使用上比较简单,可以参考MSDN中的帮助文档,也参考本文中提供的7个使用示例。

Directory.Delete菜鸟教程

对于菜鸟来说,本文中提供的7个Directory.Delete写法都将非常直观的帮您掌握Directory.Delete的用法,是一个不错的参考教程。

本文中的Directory.Delete方法示例由csref.cn整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。