├── SuperDelete
├── App.config
├── SuperDelete.licenseheader
├── Internal
│ ├── Utils.cs
│ ├── ParsedCmdLineArgs.cs
│ ├── ProgressTracker.cs
│ ├── CmdLineArgsParser.cs
│ ├── FileDeleter.cs
│ └── NativeMethods.cs
├── Properties
│ └── AssemblyInfo.cs
├── Program.cs
├── SuperDelete_35.csproj
├── SuperDelete_40.csproj
├── SuperDelete_46.csproj
├── SuperDelete_45.csproj
├── Resources.Designer.cs
└── Resources.resx
├── README.md
├── SuperDelete.sln
├── .gitignore
└── LICENSE
/SuperDelete/App.config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
--------------------------------------------------------------------------------
/SuperDelete/SuperDelete.licenseheader:
--------------------------------------------------------------------------------
1 | extensions: designer.cs generated.cs
2 | extensions: .cs .cpp .h
3 | //Sample license text.
4 | extensions: .aspx .ascx
5 | <%--
6 | Sample license text.
7 | --%>
8 | extensions: .vb
9 | 'Sample license text.
10 | extensions: .xml .config .xsd
11 |
--------------------------------------------------------------------------------
/SuperDelete/Internal/Utils.cs:
--------------------------------------------------------------------------------
1 | //Copyright 2015 Marcel Nita (marcel.nita@gmail.com)
2 | //
3 | //Licensed under the Apache License, Version 2.0 (the "License");
4 | //you may not use this file except in compliance with the License.
5 | //You may obtain a copy of the License at
6 | //
7 | // http://www.apache.org/licenses/LICENSE-2.0
8 | //
9 | //Unless required by applicable law or agreed to in writing, software
10 | //distributed under the License is distributed on an "AS IS" BASIS,
11 | //WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | //See the License for the specific language governing permissions and
13 | //limitations under the License.
14 |
15 | using System;
16 | using System.Collections.Generic;
17 | using System.Linq;
18 | using System.Text;
19 | using System.Text.RegularExpressions;
20 |
21 | namespace SuperDelete.Internal
22 | {
23 | internal static class Utils
24 | {
25 | ///
26 | /// See http://blog.codinghorror.com/shortening-long-file-paths/
27 | ///
28 | public static string PathShortener(string path)
29 | {
30 | if (path.Length > 64)
31 | {
32 | return $"{path.Substring(0, 20)}\\...\\{path.Substring(path.Length - 40, 40)}";
33 | }
34 |
35 | return path;
36 | }
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/SuperDelete/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | using System.Reflection;
2 | using System.Runtime.CompilerServices;
3 | using System.Runtime.InteropServices;
4 |
5 | // General Information about an assembly is controlled through the following
6 | // set of attributes. Change these attribute values to modify the information
7 | // associated with an assembly.
8 | [assembly: AssemblyTitle("SuperDelete")]
9 | [assembly: AssemblyDescription("")]
10 | [assembly: AssemblyConfiguration("")]
11 | [assembly: AssemblyCompany("")]
12 | [assembly: AssemblyProduct("SuperDelete")]
13 | [assembly: AssemblyCopyright("Copyright © Marcel Nita 2015-2016")]
14 | [assembly: AssemblyTrademark("")]
15 | [assembly: AssemblyCulture("")]
16 |
17 | // Setting ComVisible to false makes the types in this assembly not visible
18 | // to COM components. If you need to access a type in this assembly from
19 | // COM, set the ComVisible attribute to true on that type.
20 | [assembly: ComVisible(false)]
21 |
22 | // The following GUID is for the ID of the typelib if this project is exposed to COM
23 | [assembly: Guid("73c128eb-25b5-4c97-a363-f1ccfa2b5ddc")]
24 |
25 | // Version information for an assembly consists of the following four values:
26 | //
27 | // Major Version
28 | // Minor Version
29 | // Build Number
30 | // Revision
31 | //
32 | // You can specify all the values or you can default the Build and Revision Numbers
33 | // by using the '*' as shown below:
34 | // [assembly: AssemblyVersion("1.0.*")]
35 | [assembly: AssemblyVersion("1.2.0.0")]
36 | [assembly: AssemblyFileVersion("1.2.0.0")]
37 |
--------------------------------------------------------------------------------
/SuperDelete/Internal/ParsedCmdLineArgs.cs:
--------------------------------------------------------------------------------
1 | //Copyright 2016 Marcel Nita (marcel.nita@gmail.com)
2 | //
3 | //Licensed under the Apache License, Version 2.0 (the "License");
4 | //you may not use this file except in compliance with the License.
5 | //You may obtain a copy of the License at
6 | //
7 | // http://www.apache.org/licenses/LICENSE-2.0
8 | //
9 | //Unless required by applicable law or agreed to in writing, software
10 | //distributed under the License is distributed on an "AS IS" BASIS,
11 | //WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | //See the License for the specific language governing permissions and
13 | //limitations under the License.
14 |
15 | using System;
16 | using System.Collections.Generic;
17 | using System.Linq;
18 | using System.Text;
19 |
20 | namespace SuperDelete.Internal
21 | {
22 | internal class ParsedCmdLineArgs
23 | {
24 | public bool SilentModeEnabled { get; set; }
25 | public string FileName { get; set; }
26 |
27 | public bool BypassAcl { get; set; }
28 |
29 | public bool PrintStackTrace { get; set; }
30 |
31 | ///
32 | /// Defines all arguments and contains the logic to set the correct member with the value given
33 | ///
34 | public static readonly Dictionary> Args = new Dictionary>(StringComparer.InvariantCultureIgnoreCase)
35 | {
36 | { "-s", (a) => a.SilentModeEnabled = true },
37 | { "--silentMode", (a) => a.SilentModeEnabled = true },
38 | { "--bypassAcl", (a) => a.BypassAcl = true },
39 | { "--printStackTrace", (a) => a.PrintStackTrace = true }
40 | };
41 | }
42 | }
43 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # SuperDelete
2 |
3 | ### About
4 | A Windows command-line tool that can be used to delete files and folders with very long paths (longer than MAX_PATH 260 characters). It supports paths as long as 32767 characters.
5 | It works by using extended-length paths and the Unicode versions of the WinApi functions for enumerating and deleting files.
6 | In addition, it supports bypassing ACL checks for deleting folders if the user has administrative rights on the drive.
7 |
8 | More info about the mechanism can be found in MSDN article [Naming Files, Paths, and Namespaces](https://msdn.microsoft.com/en-us/library/windows/desktop/aa365247(v=vs.85).aspx), in section "Maximum Path Length Limitation".
9 |
10 | It's written in C#/NET and provides VS projects for building for .NET 3.5, 4.0, 4.5, 4.6
11 |
12 | ### Usage
13 |
14 | It's fairly simple. Just open a command-line window and run the tool. It takes only one parameter, which can be a full file or folder path.
15 |
16 | #### With confirmation
17 | ```
18 | SuperDelete.exe fullPathToFileOrFolder
19 | ```
20 |
21 | #### Silent mode
22 | The tool supports an additional command line argument which suppresses the confirmation message. Could be used in automating some tasks. The argument is --silent or -s.
23 |
24 | ```
25 | SuperDelete.exe --silent fullPathToFileOrFolder
26 | ```
27 |
28 | #### Bypass ACLs
29 | In the case where the user has administrative rights on the drive, the tool can bypass ACL checks and remove the file even if the user doesn't have rights in the ACL.
30 | This is useful in cases where a drive is moved from another machine or Windows installation.
31 |
32 | ```
33 | SuperDelete.exe --bypassAcl fullPathToFileOrFolder
34 | ```
35 |
36 | #### Printing stack trace
37 | If there is an exception, this will print the callstack where the exception occurred. This is mostly useful for debugging.
38 |
39 | ```
40 | SuperDelete.exe --printStackTrace fullPathToFileOrFolder
41 | ```
42 |
43 | ### Downloads
44 |
45 | The latest release is SuperDelete 1.2.0 and you can get it from the [Releases](https://github.com/marceln/SuperDelete/releases) page.
46 |
--------------------------------------------------------------------------------
/SuperDelete.sln:
--------------------------------------------------------------------------------
1 |
2 | Microsoft Visual Studio Solution File, Format Version 12.00
3 | # Visual Studio 14
4 | VisualStudioVersion = 14.0.24720.0
5 | MinimumVisualStudioVersion = 10.0.40219.1
6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SuperDelete_45", "SuperDelete\SuperDelete_45.csproj", "{73C128EB-25B5-4C97-A363-F1CCFA2B5DDC}"
7 | EndProject
8 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SuperDelete_35", "SuperDelete\SuperDelete_35.csproj", "{062F49F7-1288-4756-BBC8-DEDBFE2C837E}"
9 | EndProject
10 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SuperDelete_40", "SuperDelete\SuperDelete_40.csproj", "{86D05A38-2BAB-4053-84D7-D23601923381}"
11 | EndProject
12 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SuperDelete_46", "SuperDelete\SuperDelete_46.csproj", "{1D3684A6-9F4C-4786-A357-45A8BF5438B7}"
13 | EndProject
14 | Global
15 | GlobalSection(SolutionConfigurationPlatforms) = preSolution
16 | Debug|Any CPU = Debug|Any CPU
17 | Release|Any CPU = Release|Any CPU
18 | EndGlobalSection
19 | GlobalSection(ProjectConfigurationPlatforms) = postSolution
20 | {73C128EB-25B5-4C97-A363-F1CCFA2B5DDC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
21 | {73C128EB-25B5-4C97-A363-F1CCFA2B5DDC}.Debug|Any CPU.Build.0 = Debug|Any CPU
22 | {73C128EB-25B5-4C97-A363-F1CCFA2B5DDC}.Release|Any CPU.ActiveCfg = Release|Any CPU
23 | {73C128EB-25B5-4C97-A363-F1CCFA2B5DDC}.Release|Any CPU.Build.0 = Release|Any CPU
24 | {062F49F7-1288-4756-BBC8-DEDBFE2C837E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
25 | {062F49F7-1288-4756-BBC8-DEDBFE2C837E}.Debug|Any CPU.Build.0 = Debug|Any CPU
26 | {062F49F7-1288-4756-BBC8-DEDBFE2C837E}.Release|Any CPU.ActiveCfg = Release|Any CPU
27 | {062F49F7-1288-4756-BBC8-DEDBFE2C837E}.Release|Any CPU.Build.0 = Release|Any CPU
28 | {86D05A38-2BAB-4053-84D7-D23601923381}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
29 | {86D05A38-2BAB-4053-84D7-D23601923381}.Debug|Any CPU.Build.0 = Debug|Any CPU
30 | {86D05A38-2BAB-4053-84D7-D23601923381}.Release|Any CPU.ActiveCfg = Release|Any CPU
31 | {86D05A38-2BAB-4053-84D7-D23601923381}.Release|Any CPU.Build.0 = Release|Any CPU
32 | {1D3684A6-9F4C-4786-A357-45A8BF5438B7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
33 | {1D3684A6-9F4C-4786-A357-45A8BF5438B7}.Debug|Any CPU.Build.0 = Debug|Any CPU
34 | {1D3684A6-9F4C-4786-A357-45A8BF5438B7}.Release|Any CPU.ActiveCfg = Release|Any CPU
35 | {1D3684A6-9F4C-4786-A357-45A8BF5438B7}.Release|Any CPU.Build.0 = Release|Any CPU
36 | EndGlobalSection
37 | GlobalSection(SolutionProperties) = preSolution
38 | HideSolutionNode = FALSE
39 | EndGlobalSection
40 | EndGlobal
41 |
--------------------------------------------------------------------------------
/SuperDelete/Internal/ProgressTracker.cs:
--------------------------------------------------------------------------------
1 | //Copyright 2015 Marcel Nita (marcel.nita@gmail.com)
2 | //
3 | //Licensed under the Apache License, Version 2.0 (the "License");
4 | //you may not use this file except in compliance with the License.
5 | //You may obtain a copy of the License at
6 | //
7 | // http://www.apache.org/licenses/LICENSE-2.0
8 | //
9 | //Unless required by applicable law or agreed to in writing, software
10 | //distributed under the License is distributed on an "AS IS" BASIS,
11 | //WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | //See the License for the specific language governing permissions and
13 | //limitations under the License.
14 |
15 | using System;
16 | using System.Diagnostics;
17 | using System.Threading;
18 |
19 | namespace SuperDelete.Internal
20 | {
21 | internal class ProgressTracker
22 | {
23 | #region Singleton
24 |
25 | private ProgressTracker()
26 | {
27 | _durationTracker = new Stopwatch();
28 | _durationTracker.Start();
29 | }
30 |
31 | private static ProgressTracker _instance;
32 |
33 | public static ProgressTracker Instance
34 | {
35 | get
36 | {
37 | if (_instance == null)
38 | {
39 | _instance = new ProgressTracker();
40 | }
41 |
42 | return _instance;
43 | }
44 | }
45 |
46 | #endregion
47 |
48 | #region Private data
49 |
50 | private volatile int _numberOfDeletedFiles;
51 | private volatile int _numberOfDeletedFolders;
52 | private Stopwatch _durationTracker;
53 |
54 | #endregion
55 |
56 | #region API
57 | public void LogEntry(string fileName, bool isFolder)
58 | {
59 | if (isFolder)
60 | {
61 | Interlocked.Increment(ref _numberOfDeletedFolders);
62 | }
63 | else
64 | {
65 | Interlocked.Increment(ref _numberOfDeletedFiles);
66 | }
67 |
68 | Console.Write($"\rDeleting {Utils.PathShortener(fileName)}\t\t\t\t");
69 | }
70 |
71 | public void Stop()
72 | {
73 | _durationTracker.Stop();
74 | var duration = TimeSpan.FromMilliseconds(_durationTracker.ElapsedMilliseconds);
75 | Console.WriteLine($"\rDone. Deleted {_numberOfDeletedFiles} files and {_numberOfDeletedFolders} folders in {duration}.\t\t\t\t");
76 | }
77 |
78 | #endregion
79 | }
80 | }
81 |
--------------------------------------------------------------------------------
/SuperDelete/Program.cs:
--------------------------------------------------------------------------------
1 | //Copyright 2015 Marcel Nita (marcel.nita@gmail.com)
2 | //
3 | //Licensed under the Apache License, Version 2.0 (the "License");
4 | //you may not use this file except in compliance with the License.
5 | //You may obtain a copy of the License at
6 | //
7 | // http://www.apache.org/licenses/LICENSE-2.0
8 | //
9 | //Unless required by applicable law or agreed to in writing, software
10 | //distributed under the License is distributed on an "AS IS" BASIS,
11 | //WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | //See the License for the specific language governing permissions and
13 | //limitations under the License.
14 |
15 | using SuperDelete.Internal;
16 | using System;
17 | using System.ComponentModel;
18 | using System.IO;
19 | using System.Linq;
20 | using System.Runtime.InteropServices;
21 | using System.Text;
22 |
23 | namespace SuperDelete
24 | {
25 | internal class Program
26 | {
27 | public static void Main(string[] args)
28 | {
29 | ParsedCmdLineArgs parsedArgs;
30 | try
31 | {
32 | parsedArgs = CmdLineArgsParser.Parse(args);
33 | }
34 | catch (CmdLineArgsParser.InvalidCmdLineException e)
35 | {
36 | CmdLineArgsParser.PrintUsage(e);
37 | return;
38 | }
39 |
40 | try
41 | {
42 | // get the full path for confirmation
43 | string filename = FileDeleter.GetFullPath(parsedArgs.FileName);
44 |
45 | //If silent mode is not specified
46 | if (!parsedArgs.SilentModeEnabled)
47 | {
48 | Console.WriteLine(Resources.ConfirmationLine, filename);
49 | var keyInfo = Console.ReadKey();
50 | if (keyInfo.Key != ConsoleKey.Y && keyInfo.Key != ConsoleKey.Enter)
51 | {
52 | return;
53 | }
54 | }
55 |
56 | FileDeleter.Delete(filename, parsedArgs.BypassAcl);
57 | }
58 | catch (Exception e)
59 | {
60 | Console.WriteLine();
61 |
62 | if (parsedArgs.PrintStackTrace)
63 | {
64 | Console.WriteLine($"Error: {e.ToString()}");
65 | }
66 | else
67 | {
68 | Console.WriteLine($"Error: {e.Message}");
69 | }
70 | }
71 | finally
72 | {
73 | ProgressTracker.Instance.Stop();
74 | }
75 | }
76 | }
77 | }
78 |
--------------------------------------------------------------------------------
/SuperDelete/Internal/CmdLineArgsParser.cs:
--------------------------------------------------------------------------------
1 | //Copyright 2016 Marcel Nita (marcel.nita@gmail.com)
2 | //
3 | //Licensed under the Apache License, Version 2.0 (the "License");
4 | //you may not use this file except in compliance with the License.
5 | //You may obtain a copy of the License at
6 | //
7 | // http://www.apache.org/licenses/LICENSE-2.0
8 | //
9 | //Unless required by applicable law or agreed to in writing, software
10 | //distributed under the License is distributed on an "AS IS" BASIS,
11 | //WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | //See the License for the specific language governing permissions and
13 | //limitations under the License.
14 |
15 |
16 | using System;
17 | using System.Collections.Generic;
18 | using System.Linq;
19 | using System.Reflection;
20 | using System.Text;
21 |
22 | namespace SuperDelete.Internal
23 | {
24 | internal class CmdLineArgsParser
25 | {
26 | public class InvalidCmdLineException : Exception
27 | {
28 | public InvalidCmdLineException(string message) : base(message)
29 | {
30 | }
31 | }
32 |
33 | public static void PrintUsage(CmdLineArgsParser.InvalidCmdLineException e)
34 | {
35 | var appVersion = Assembly.
36 | GetExecutingAssembly().
37 | GetName().
38 | Version.
39 | ToString();
40 |
41 | var versionLine = String.Format(Resources.VersionLine, appVersion);
42 | Console.WriteLine(versionLine);
43 |
44 | StringBuilder args = new StringBuilder();
45 | foreach (var arg in ParsedCmdLineArgs.Args.Keys)
46 | {
47 | args.AppendFormat("[{0}]", arg);
48 | }
49 |
50 | Console.WriteLine(Resources.UsageLine, e.Message, args.ToString());
51 | }
52 |
53 | public static ParsedCmdLineArgs Parse(string[] args)
54 | {
55 | var result = new ParsedCmdLineArgs();
56 |
57 | //Check if we have any args
58 | foreach(string arg in args)
59 | {
60 | if (arg.StartsWith("-"))
61 | {
62 | // this is a switch
63 | Action a;
64 |
65 | if (ParsedCmdLineArgs.Args.TryGetValue(arg, out a))
66 | {
67 | a(result);
68 | }
69 | else
70 | {
71 | throw new InvalidCmdLineException(string.Format(Resources.InvalidSwitchError, arg));
72 | }
73 | }
74 | else
75 | {
76 | if (result.FileName == null)
77 | {
78 | result.FileName = arg;
79 | }
80 | else
81 | {
82 | throw new InvalidCmdLineException(Resources.TooManyFilenamesError);
83 | }
84 | }
85 | }
86 |
87 | if(result.FileName == null)
88 | {
89 | throw new InvalidCmdLineException(Resources.NoFilenamesSpecified);
90 | }
91 |
92 | return result;
93 | }
94 | }
95 | }
96 |
--------------------------------------------------------------------------------
/SuperDelete/SuperDelete_35.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | Debug
6 | AnyCPU
7 | {062F49F7-1288-4756-BBC8-DEDBFE2C837E}
8 | Exe
9 | Properties
10 | SuperDelete
11 | SuperDelete
12 | v3.5
13 | 512
14 |
15 | true
16 |
17 |
18 | AnyCPU
19 | true
20 | full
21 | false
22 | bin\Debug35\
23 | obj35\
24 | DEBUG;TRACE
25 | prompt
26 | 4
27 |
28 |
29 | AnyCPU
30 | pdbonly
31 | true
32 | bin\Release35\
33 | obj35\
34 | TRACE
35 | prompt
36 | 4
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
50 |
51 |
52 |
53 |
54 |
55 |
56 | True
57 | True
58 | Resources.resx
59 |
60 |
61 |
62 |
63 |
64 |
65 |
66 | ResXFileCodeGenerator
67 | Resources.Designer.cs
68 |
69 |
70 |
71 |
78 |
--------------------------------------------------------------------------------
/SuperDelete/SuperDelete_40.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | Debug
6 | AnyCPU
7 | {86D05A38-2BAB-4053-84D7-D23601923381}
8 | Exe
9 | Properties
10 | SuperDelete
11 | SuperDelete
12 | v4.0
13 | 512
14 |
15 | true
16 |
17 |
18 | AnyCPU
19 | true
20 | full
21 | false
22 | bin\Debug40\
23 | obj40\
24 | DEBUG;TRACE
25 | prompt
26 | 4
27 |
28 |
29 | AnyCPU
30 | pdbonly
31 | true
32 | bin\Release40\
33 | obj40\
34 | TRACE
35 | prompt
36 | 4
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
50 |
51 |
52 |
53 |
54 |
55 |
56 |
57 | True
58 | True
59 | Resources.resx
60 |
61 |
62 |
63 |
64 |
65 |
66 |
67 | ResXFileCodeGenerator
68 | Resources.Designer.cs
69 |
70 |
71 |
72 |
79 |
--------------------------------------------------------------------------------
/SuperDelete/SuperDelete_46.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | Debug
6 | AnyCPU
7 | {1D3684A6-9F4C-4786-A357-45A8BF5438B7}
8 | Exe
9 | Properties
10 | SuperDelete
11 | SuperDelete
12 | v4.6
13 | 512
14 |
15 | true
16 |
17 |
18 | AnyCPU
19 | true
20 | full
21 | false
22 | bin\Debug46\
23 | obj46\
24 | DEBUG;TRACE
25 | prompt
26 | 4
27 |
28 |
29 | AnyCPU
30 | pdbonly
31 | true
32 | bin\Release46\
33 | obj46\
34 | TRACE
35 | prompt
36 | 4
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
50 |
51 |
52 |
53 |
54 |
55 |
56 |
57 |
58 | True
59 | True
60 | Resources.resx
61 |
62 |
63 |
64 |
65 |
66 |
67 |
68 | ResXFileCodeGenerator
69 | Resources.Designer.cs
70 |
71 |
72 |
73 |
80 |
--------------------------------------------------------------------------------
/SuperDelete/SuperDelete_45.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | Debug
6 | AnyCPU
7 | {73C128EB-25B5-4C97-A363-F1CCFA2B5DDC}
8 | Exe
9 | Properties
10 | SuperDelete
11 | SuperDelete
12 | v4.5
13 | 512
14 | true
15 |
16 |
17 | AnyCPU
18 | true
19 | full
20 | false
21 | bin\Debug45\
22 | obj45\
23 | DEBUG;TRACE
24 | prompt
25 | 4
26 |
27 |
28 | AnyCPU
29 | pdbonly
30 | true
31 | bin\Release45\
32 | obj45\
33 | TRACE
34 | prompt
35 | 4
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
50 |
51 |
52 |
53 |
54 |
55 |
56 |
57 | True
58 | True
59 | Resources.resx
60 |
61 |
62 |
63 |
64 |
65 |
66 |
67 |
68 | ResXFileCodeGenerator
69 | Resources.Designer.cs
70 |
71 |
72 |
73 |
80 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | ## Ignore Visual Studio temporary files, build results, and
2 | ## files generated by popular Visual Studio add-ons.
3 |
4 | # User-specific files
5 | *.suo
6 | *.user
7 | *.userosscache
8 | *.sln.docstates
9 |
10 | # User-specific files (MonoDevelop/Xamarin Studio)
11 | *.userprefs
12 |
13 | # Build results
14 | [Dd]ebug/
15 | [Dd]ebug35/
16 | [Dd]ebug40/
17 | [Dd]ebug45/
18 | [Dd]ebug46/
19 | [Dd]ebugPublic/
20 | [Rr]elease/
21 | [Rr]eleases/
22 | [Rr]elease35/
23 | [Rr]elease40/
24 | [Rr]elease45/
25 | [Rr]elease46/
26 | x64/
27 | x86/
28 | build/
29 | bld/
30 | [Bb]in/
31 | [Oo]bj/
32 | [Oo]bj35/
33 | [Oo]bj40/
34 | [Oo]bj45/
35 | [Oo]bj46/
36 |
37 | # Visual Studio 2015 cache/options directory
38 | .vs/
39 | # Uncomment if you have tasks that create the project's static files in wwwroot
40 | #wwwroot/
41 |
42 | # MSTest test Results
43 | [Tt]est[Rr]esult*/
44 | [Bb]uild[Ll]og.*
45 |
46 | # NUNIT
47 | *.VisualState.xml
48 | TestResult.xml
49 |
50 | # Build Results of an ATL Project
51 | [Dd]ebugPS/
52 | [Rr]eleasePS/
53 | dlldata.c
54 |
55 | # DNX
56 | project.lock.json
57 | artifacts/
58 |
59 | *_i.c
60 | *_p.c
61 | *_i.h
62 | *.ilk
63 | *.meta
64 | *.obj
65 | *.pch
66 | *.pdb
67 | *.pgc
68 | *.pgd
69 | *.rsp
70 | *.sbr
71 | *.tlb
72 | *.tli
73 | *.tlh
74 | *.tmp
75 | *.tmp_proj
76 | *.log
77 | *.vspscc
78 | *.vssscc
79 | .builds
80 | *.pidb
81 | *.svclog
82 | *.scc
83 |
84 | # Chutzpah Test files
85 | _Chutzpah*
86 |
87 | # Visual C++ cache files
88 | ipch/
89 | *.aps
90 | *.ncb
91 | *.opendb
92 | *.opensdf
93 | *.sdf
94 | *.cachefile
95 |
96 | # Visual Studio profiler
97 | *.psess
98 | *.vsp
99 | *.vspx
100 | *.sap
101 |
102 | # TFS 2012 Local Workspace
103 | $tf/
104 |
105 | # Guidance Automation Toolkit
106 | *.gpState
107 |
108 | # ReSharper is a .NET coding add-in
109 | _ReSharper*/
110 | *.[Rr]e[Ss]harper
111 | *.DotSettings.user
112 |
113 | # JustCode is a .NET coding add-in
114 | .JustCode
115 |
116 | # TeamCity is a build add-in
117 | _TeamCity*
118 |
119 | # DotCover is a Code Coverage Tool
120 | *.dotCover
121 |
122 | # NCrunch
123 | _NCrunch_*
124 | .*crunch*.local.xml
125 | nCrunchTemp_*
126 |
127 | # MightyMoose
128 | *.mm.*
129 | AutoTest.Net/
130 |
131 | # Web workbench (sass)
132 | .sass-cache/
133 |
134 | # Installshield output folder
135 | [Ee]xpress/
136 |
137 | # DocProject is a documentation generator add-in
138 | DocProject/buildhelp/
139 | DocProject/Help/*.HxT
140 | DocProject/Help/*.HxC
141 | DocProject/Help/*.hhc
142 | DocProject/Help/*.hhk
143 | DocProject/Help/*.hhp
144 | DocProject/Help/Html2
145 | DocProject/Help/html
146 |
147 | # Click-Once directory
148 | publish/
149 |
150 | # Publish Web Output
151 | *.[Pp]ublish.xml
152 | *.azurePubxml
153 | # TODO: Comment the next line if you want to checkin your web deploy settings
154 | # but database connection strings (with potential passwords) will be unencrypted
155 | *.pubxml
156 | *.publishproj
157 |
158 | # NuGet Packages
159 | *.nupkg
160 | # The packages folder can be ignored because of Package Restore
161 | **/packages/*
162 | # except build/, which is used as an MSBuild target.
163 | !**/packages/build/
164 | # Uncomment if necessary however generally it will be regenerated when needed
165 | #!**/packages/repositories.config
166 |
167 | # Windows Azure Build Output
168 | csx/
169 | *.build.csdef
170 |
171 | # Windows Azure Emulator
172 | ecf/
173 | rcf/
174 |
175 | # Windows Store app package directory
176 | AppPackages/
177 |
178 | # Visual Studio cache files
179 | # files ending in .cache can be ignored
180 | *.[Cc]ache
181 | # but keep track of directories ending in .cache
182 | !*.[Cc]ache/
183 |
184 | # Others
185 | ClientBin/
186 | [Ss]tyle[Cc]op.*
187 | ~$*
188 | *~
189 | *.dbmdl
190 | *.dbproj.schemaview
191 | *.pfx
192 | *.publishsettings
193 | node_modules/
194 | orleans.codegen.cs
195 |
196 | # RIA/Silverlight projects
197 | Generated_Code/
198 |
199 | # Backup & report files from converting an old project file
200 | # to a newer Visual Studio version. Backup files are not needed,
201 | # because we have git ;-)
202 | _UpgradeReport_Files/
203 | Backup*/
204 | UpgradeLog*.XML
205 | UpgradeLog*.htm
206 |
207 | # SQL Server files
208 | *.mdf
209 | *.ldf
210 |
211 | # Business Intelligence projects
212 | *.rdl.data
213 | *.bim.layout
214 | *.bim_*.settings
215 |
216 | # Microsoft Fakes
217 | FakesAssemblies/
218 |
219 | # GhostDoc plugin setting file
220 | *.GhostDoc.xml
221 |
222 | # Node.js Tools for Visual Studio
223 | .ntvs_analysis.dat
224 |
225 | # Visual Studio 6 build log
226 | *.plg
227 |
228 | # Visual Studio 6 workspace options file
229 | *.opt
230 |
231 | # Visual Studio LightSwitch build output
232 | **/*.HTMLClient/GeneratedArtifacts
233 | **/*.DesktopClient/GeneratedArtifacts
234 | **/*.DesktopClient/ModelManifest.xml
235 | **/*.Server/GeneratedArtifacts
236 | **/*.Server/ModelManifest.xml
237 | _Pvt_Extensions
238 |
239 | # Paket dependency manager
240 | .paket/paket.exe
241 |
242 | # FAKE - F# Make
243 | .fake/
--------------------------------------------------------------------------------
/SuperDelete/Resources.Designer.cs:
--------------------------------------------------------------------------------
1 | //------------------------------------------------------------------------------
2 | //
3 | // This code was generated by a tool.
4 | // Runtime Version:4.0.30319.42000
5 | //
6 | // Changes to this file may cause incorrect behavior and will be lost if
7 | // the code is regenerated.
8 | //
9 | //------------------------------------------------------------------------------
10 |
11 | namespace SuperDelete {
12 | using System;
13 |
14 |
15 | ///
16 | /// A strongly-typed resource class, for looking up localized strings, etc.
17 | ///
18 | // This class was auto-generated by the StronglyTypedResourceBuilder
19 | // class via a tool like ResGen or Visual Studio.
20 | // To add or remove a member, edit your .ResX file then rerun ResGen
21 | // with the /str option, or rebuild your VS project.
22 | [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
23 | [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
24 | [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
25 | internal class Resources {
26 |
27 | private static global::System.Resources.ResourceManager resourceMan;
28 |
29 | private static global::System.Globalization.CultureInfo resourceCulture;
30 |
31 | [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
32 | internal Resources() {
33 | }
34 |
35 | ///
36 | /// Returns the cached ResourceManager instance used by this class.
37 | ///
38 | [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
39 | internal static global::System.Resources.ResourceManager ResourceManager {
40 | get {
41 | if (object.ReferenceEquals(resourceMan, null)) {
42 | global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("SuperDelete.Resources", typeof(Resources).Assembly);
43 | resourceMan = temp;
44 | }
45 | return resourceMan;
46 | }
47 | }
48 |
49 | ///
50 | /// Overrides the current thread's CurrentUICulture property for all
51 | /// resource lookups using this strongly typed resource class.
52 | ///
53 | [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
54 | internal static global::System.Globalization.CultureInfo Culture {
55 | get {
56 | return resourceCulture;
57 | }
58 | set {
59 | resourceCulture = value;
60 | }
61 | }
62 |
63 | ///
64 | /// Looks up a localized string similar to Are you sure you want to delete file/folder at path {0}? (Y/n).
65 | ///
66 | internal static string ConfirmationLine {
67 | get {
68 | return ResourceManager.GetString("ConfirmationLine", resourceCulture);
69 | }
70 | }
71 |
72 | ///
73 | /// Looks up a localized string similar to Invalid switch {0}.
74 | ///
75 | internal static string InvalidSwitchError {
76 | get {
77 | return ResourceManager.GetString("InvalidSwitchError", resourceCulture);
78 | }
79 | }
80 |
81 | ///
82 | /// Looks up a localized string similar to No file/directory specified.
83 | ///
84 | internal static string NoFilenamesSpecified {
85 | get {
86 | return ResourceManager.GetString("NoFilenamesSpecified", resourceCulture);
87 | }
88 | }
89 |
90 | ///
91 | /// Looks up a localized string similar to Too many filenames specified.
92 | ///
93 | internal static string TooManyFilenamesError {
94 | get {
95 | return ResourceManager.GetString("TooManyFilenamesError", resourceCulture);
96 | }
97 | }
98 |
99 | ///
100 | /// Looks up a localized string similar to Error: {0} Usage: SuperDelete.exe {1} <file or folder path>.
101 | ///
102 | internal static string UsageLine {
103 | get {
104 | return ResourceManager.GetString("UsageLine", resourceCulture);
105 | }
106 | }
107 |
108 | ///
109 | /// Looks up a localized string similar to SuperDelete version {0}..
110 | ///
111 | internal static string VersionLine {
112 | get {
113 | return ResourceManager.GetString("VersionLine", resourceCulture);
114 | }
115 | }
116 | }
117 | }
118 |
--------------------------------------------------------------------------------
/SuperDelete/Resources.resx:
--------------------------------------------------------------------------------
1 |
2 |
3 |
62 |
63 |
64 |
65 |
66 |
67 |
68 |
69 |
70 |
71 |
72 |
73 |
74 |
75 |
76 |
77 |
78 |
79 |
80 |
81 |
82 |
83 |
84 |
85 |
86 |
87 |
88 |
89 |
90 |
91 |
92 |
93 |
94 |
95 |
96 |
97 |
98 |
99 |
100 |
101 |
102 |
103 |
104 |
105 |
106 |
107 |
108 |
109 | text/microsoft-resx
110 |
111 |
112 | 2.0
113 |
114 |
115 | System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
116 |
117 |
118 | System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
119 |
120 |
121 | Are you sure you want to delete file/folder at path {0}? (Y/n)
122 |
123 |
124 | Invalid switch {0}
125 |
126 |
127 | No file/directory specified
128 |
129 |
130 | Too many filenames specified
131 |
132 |
133 | Error: {0} Usage: SuperDelete.exe {1} <file or folder path>
134 |
135 |
136 | SuperDelete version {0}.
137 |
138 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "{}"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright {yyyy} {name of copyright owner}
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
203 |
--------------------------------------------------------------------------------
/SuperDelete/Internal/FileDeleter.cs:
--------------------------------------------------------------------------------
1 | //Copyright 2015 Marcel Nita (marcel.nita@gmail.com)
2 | //
3 | //Licensed under the Apache License, Version 2.0 (the "License");
4 | //you may not use this file except in compliance with the License.
5 | //You may obtain a copy of the License at
6 | //
7 | // http://www.apache.org/licenses/LICENSE-2.0
8 | //
9 | //Unless required by applicable law or agreed to in writing, software
10 | //distributed under the License is distributed on an "AS IS" BASIS,
11 | //WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | //See the License for the specific language governing permissions and
13 | //limitations under the License.
14 |
15 | using System;
16 | using System.Collections.Generic;
17 | using System.ComponentModel;
18 | using System.IO;
19 | using System.Runtime.InteropServices;
20 | using System.Text;
21 |
22 | using Microsoft.Win32.SafeHandles;
23 |
24 | namespace SuperDelete.Internal
25 | {
26 | internal class FileDeleter
27 | {
28 | private const string FileNamePrefix = "\\\\?\\";
29 |
30 | private class DirectoryWithAttributes
31 | {
32 | public string Directory;
33 | public NativeMethods.FileAttributes Attributes;
34 | }
35 |
36 | public static string GetFullPath(string path)
37 | {
38 | // check to see if this is an absolute path, if so, we don't need to do anything
39 | // starts with \\blahblah or is in the form x:\blahblah
40 | if (path.StartsWith(@"\\") || (path.Length >= 3 && path.Substring(1,2) == @":\"))
41 | {
42 | return path;
43 | }
44 |
45 | // resolve to absolute path to avoid confusion since long filename API won't accept relative paths
46 | StringBuilder fullName = new StringBuilder(32768);
47 |
48 | if (NativeMethods.GetFullPathNameW(path, fullName.MaxCapacity, fullName, IntPtr.Zero) == 0)
49 | {
50 | ThrowLastErrorException("Could not convert relative to absolute path. Try specifying absolute path. {0} ", path);
51 | }
52 |
53 | return fullName.ToString();
54 | }
55 |
56 | ///
57 | /// Deletes the specified directory or filename
58 | ///
59 | /// Path to delete
60 | /// If we should bypass ACLs
61 | public static void Delete(string path, bool bypassAcl)
62 | {
63 | // bypassing ACLs requires first to enable these privileges. If you are not an admin, you'll get an error here
64 | if (bypassAcl)
65 | {
66 | EnablePrivilege("SeBackupPrivilege");
67 | EnablePrivilege("SeRestorePrivilege");
68 | EnablePrivilege("SeTakeOwnershipPrivilege");
69 | EnablePrivilege("SeSecurityPrivilege");
70 | }
71 |
72 | uint fileAttrs = NativeMethods.GetFileAttributesW(EnsureFileName(path));
73 | if ((fileAttrs & (uint)FileAttributes.Directory) == (uint)FileAttributes.Directory)
74 | {
75 | DeleteFolder(path, bypassAcl, 0);
76 | }
77 | else
78 | {
79 | DeleteSingleFile(path, bypassAcl);
80 | }
81 | }
82 |
83 | ///
84 | /// Enables a specified privilege. Required to perform certain administrative actions in Windows.
85 | ///
86 | /// Name of the privilege
87 | private static void EnablePrivilege(string priv)
88 | {
89 | NativeMethods.LUID privLuid;
90 | if (!NativeMethods.LookupPrivilegeValue(null, priv, out privLuid))
91 | {
92 | ThrowLastErrorException("Could not look up privilege {0}", priv);
93 | }
94 |
95 | NativeMethods.SafeAccessTokenHandle token;
96 | if (!NativeMethods.OpenProcessToken(NativeMethods.GetCurrentProcess(), System.Security.Principal.TokenAccessLevels.AdjustPrivileges, out token))
97 | {
98 | ThrowLastErrorException("Could not open process token");
99 | }
100 |
101 | using (token)
102 | {
103 | NativeMethods.TOKEN_PRIVILEGE tokenpriv = new NativeMethods.TOKEN_PRIVILEGE();
104 | tokenpriv.PrivilegeCount = 1;
105 | tokenpriv.Privilege.Luid = privLuid;
106 | tokenpriv.Privilege.Attributes = NativeMethods.SE_PRIVILEGE_ENABLED;
107 | if (!NativeMethods.AdjustTokenPrivileges(token, false, ref tokenpriv, 0, IntPtr.Zero, IntPtr.Zero))
108 | {
109 | ThrowLastErrorException("Could not not adjust token for privilege {0}", priv);
110 | }
111 |
112 | int lastError = Marshal.GetLastWin32Error();
113 | if (lastError != 0)
114 | {
115 | ThrowLastErrorException("Could not not enable token for privilege {0}. Are you running as Administrator?", priv);
116 | }
117 | }
118 | }
119 |
120 | private static void DeleteSingleFile(string filePath, bool bypassAcl)
121 | {
122 | ProgressTracker.Instance.LogEntry(filePath, false);
123 | filePath = EnsureFileName(filePath);
124 |
125 | if (bypassAcl)
126 | {
127 | DeleteFileBackupSemantics(filePath);
128 | }
129 | else
130 | {
131 | if (!NativeMethods.DeleteFileW(filePath))
132 | {
133 | ThrowLastErrorException("Failed to delete file {0}", filePath);
134 | }
135 | }
136 | }
137 |
138 | ///
139 | /// Deletes a file using backup semantics. This bypasses ACLs if the user
140 | /// has administrative rights
141 | ///
142 | ///
143 | ///
144 | private unsafe static void DeleteFileBackupSemantics(string lpFileName)
145 | {
146 | using (SafeFileHandle fileHandle = NativeMethods.CreateFile(lpFileName,
147 | NativeMethods.EFileAccess.DELETE,
148 | FileShare.None,
149 | IntPtr.Zero,
150 | FileMode.Open,
151 | (int)(NativeMethods.FileAttributes.DeleteOnClose | NativeMethods.FileAttributes.BackupSemantics),
152 | IntPtr.Zero))
153 | {
154 | if (fileHandle.IsInvalid)
155 | {
156 | ThrowLastErrorException("Failed attempting open file {0} with backup semantics", lpFileName);
157 | }
158 |
159 | var dispositionInfo = new NativeMethods.FILE_DISPOSITION_INFORMATION();
160 | dispositionInfo.DeleteFile = true;
161 |
162 | var ioStatusBlock = new NativeMethods.IO_STATUS_BLOCK();
163 | int retVal = NativeMethods.NtSetInformationFile(fileHandle, ref ioStatusBlock, new IntPtr(&dispositionInfo), Marshal.SizeOf(dispositionInfo), NativeMethods.FILE_INFORMATION_CLASS.FileDispositionInformation);
164 | if (retVal != 0)
165 | {
166 | ThrowLastErrorException(NativeMethods.RtlNtStatusToDosError(retVal), "Couldn't set delete disposition on {0}", lpFileName);
167 | }
168 | }
169 | }
170 |
171 | private static void DeleteFolder(string folderPath, bool bypassAclCheck, NativeMethods.FileAttributes parentAttributes)
172 | {
173 | var baseFolderPath = EnsureFileName(folderPath);
174 | var searchTerm = Path.Combine(baseFolderPath, "*");
175 |
176 | var directories = new List();
177 |
178 | NativeMethods.WIN32_FIND_DATAW findInfo;
179 | NativeMethods.FindFileSafeHandle searchHandle = NativeMethods.FindFirstFileW(searchTerm, out findInfo);
180 | if (searchHandle.IsInvalid)
181 | {
182 | ThrowLastErrorException("Error locating files in {0}", searchTerm);
183 | }
184 |
185 | using (searchHandle)
186 | {
187 | do
188 | {
189 | var isDirectory = ((uint)findInfo.dwFileAttributes & (uint)NativeMethods.FileAttributes.Directory) == (uint)NativeMethods.FileAttributes.Directory;
190 | var fullFilePath = Path.Combine(folderPath, findInfo.cFileName);
191 |
192 | if ((findInfo.dwFileAttributes & NativeMethods.FileAttributes.ReparsePoint) != 0)
193 | {
194 | // reparse points can be removed directly. If we attempt to follow down into the reprase
195 | // point, then we start getting weird error messages when unexpected files get deleted
196 | // or permissions cannot be obtained.
197 |
198 | if (!NativeMethods.RemoveDirectoryW(fullFilePath))
199 | {
200 | ThrowLastErrorException("Failed to remove reparse point {0}", fullFilePath);
201 | }
202 | }
203 | else if (isDirectory)
204 | {
205 | if (string.Compare(findInfo.cFileName, ".", StringComparison.InvariantCultureIgnoreCase) == 0 ||
206 | string.Compare(findInfo.cFileName, "..", StringComparison.InvariantCultureIgnoreCase) == 0)
207 | {
208 | continue;
209 | }
210 |
211 | directories.Add(new DirectoryWithAttributes { Directory = fullFilePath, Attributes = findInfo.dwFileAttributes });
212 | }
213 | else
214 | {
215 | RemoveReadonlyAttribute(fullFilePath, findInfo.dwFileAttributes);
216 |
217 | DeleteSingleFile(fullFilePath, bypassAclCheck);
218 | }
219 |
220 | } while (NativeMethods.FindNextFileW(searchHandle, out findInfo));
221 | }
222 |
223 | foreach (var directory in directories)
224 | {
225 | RemoveReadonlyAttribute(directory.Directory, directory.Attributes);
226 |
227 | DeleteFolder(directory.Directory, bypassAclCheck, directory.Attributes);
228 | }
229 |
230 | ProgressTracker.Instance.LogEntry(baseFolderPath, true);
231 | if (!NativeMethods.RemoveDirectoryW(baseFolderPath))
232 | {
233 | ThrowLastErrorException("Failed to remove directory {0}", baseFolderPath);
234 | }
235 | }
236 |
237 | ///
238 | /// Removes read only attribute from file or directory if it has one
239 | ///
240 | ///
241 | ///
242 | private static unsafe void RemoveReadonlyAttribute(string filename, NativeMethods.FileAttributes currentAttributes)
243 | {
244 | NativeMethods.FileAttributes attributesToRemove = NativeMethods.FileAttributes.Readonly;
245 |
246 | if (((uint)currentAttributes & (uint)attributesToRemove) != 0)
247 | {
248 | var newAttributes = (uint)(currentAttributes & (~attributesToRemove));
249 |
250 | if (!NativeMethods.SetFileAttributesW(EnsureFileName(filename), newAttributes))
251 | {
252 | ThrowLastErrorException("Failed to remove {0} attribute on {1}", (currentAttributes & attributesToRemove), filename);
253 | }
254 | }
255 | }
256 |
257 | private static void ThrowLastErrorException(string message, params object[] args)
258 | {
259 | ThrowLastErrorException(Marshal.GetLastWin32Error(), message, args);
260 | }
261 |
262 | private static void ThrowLastErrorException(int error, string message, params object[] args)
263 | {
264 | string errorMessage = new Win32Exception(error).Message;
265 |
266 | throw new Win32Exception(error, errorMessage + ". " + string.Format(message, args));
267 | }
268 |
269 | private static string EnsureFileName(string fileName)
270 | {
271 | if (fileName.StartsWith(FileNamePrefix))
272 | {
273 | return fileName;
274 | }
275 |
276 | return $"{FileNamePrefix}{fileName}";
277 | }
278 | }
279 | }
280 |
--------------------------------------------------------------------------------
/SuperDelete/Internal/NativeMethods.cs:
--------------------------------------------------------------------------------
1 | //Copyright 2015 Marcel Nita (marcel.nita@gmail.com)
2 | //
3 | //Licensed under the Apache License, Version 2.0 (the "License");
4 | //you may not use this file except in compliance with the License.
5 | //You may obtain a copy of the License at
6 | //
7 | // http://www.apache.org/licenses/LICENSE-2.0
8 | //
9 | //Unless required by applicable law or agreed to in writing, software
10 | //distributed under the License is distributed on an "AS IS" BASIS,
11 | //WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | //See the License for the specific language governing permissions and
13 | //limitations under the License.
14 |
15 | using Microsoft.Win32.SafeHandles;
16 | using System;
17 | using System.IO;
18 | using System.Runtime.InteropServices;
19 | using System.Security.Principal;
20 | using System.Text;
21 |
22 | namespace SuperDelete.Internal
23 | {
24 | ///
25 | ///
26 | ///
27 | internal static class NativeMethods
28 | {
29 | public const int MAX_PATH = 260;
30 | public const int MAX_ALTERNATE = 14;
31 |
32 | public class FindFileSafeHandle : SafeHandleMinusOneIsInvalid
33 | {
34 | FindFileSafeHandle() : base(true)
35 | {
36 | }
37 |
38 | protected override bool ReleaseHandle()
39 | {
40 | NativeMethods.FindClose(this.handle);
41 | return true;
42 | }
43 | }
44 |
45 | // Introduce this handle to replace internal SafeTokenHandle,
46 | // which is mainly used to hold Windows thread or process access token
47 | public sealed class SafeAccessTokenHandle : SafeHandle
48 | {
49 | private SafeAccessTokenHandle()
50 | : base(IntPtr.Zero, true)
51 | { }
52 |
53 | // 0 is an Invalid Handle
54 | public SafeAccessTokenHandle(IntPtr handle)
55 | : base(IntPtr.Zero, true)
56 | {
57 | SetHandle(handle);
58 | }
59 |
60 | public static SafeAccessTokenHandle InvalidHandle
61 | {
62 | get { return new SafeAccessTokenHandle(IntPtr.Zero); }
63 | }
64 |
65 | public override bool IsInvalid
66 | {
67 | get { return handle == IntPtr.Zero || handle == new IntPtr(-1); }
68 | }
69 |
70 | protected override bool ReleaseHandle()
71 | {
72 | return NativeMethods.CloseHandle(handle);
73 | }
74 | }
75 |
76 | public const uint SE_PRIVILEGE_ENABLED = 0x00000002;
77 |
78 | public static readonly IntPtr INVALID_HANDLE_VALUE = new IntPtr(-1);
79 |
80 | [Flags]
81 | public enum EFileAccess : uint
82 | {
83 | GENERIC_READ = 0x80000000,
84 | GENERIC_WRITE = 0x40000000,
85 | GENERIC_EXECUTE = 0x20000000,
86 | GENERIC_ALL = 0x10000000,
87 |
88 | DELETE = 0x00010000,
89 | READ_CONTROL = 0x00020000,
90 | WRITE_DAC = 0x00040000,
91 | WRITE_OWNER = 0x00080000,
92 | SYNCHRONIZE = 0x00100000,
93 |
94 | FILE_READ_DATA = 0x0001, // file & pipe
95 | FILE_LIST_DIRECTORY = 0x0001, // directory
96 |
97 | FILE_WRITE_DATA = 0x0002, // file & pipe
98 | FILE_ADD_FILE = 0x0002, // directory
99 |
100 | FILE_APPEND_DATA = 0x0004, // file
101 | FILE_ADD_SUBDIRECTORY = 0x0004, // directory
102 | FILE_CREATE_PIPE_INSTANCE = 0x0004, // named pipe
103 |
104 | FILE_READ_EA = 0x0008, // file & directory
105 |
106 | FILE_WRITE_EA = 0x0010, // file & directory
107 |
108 | FILE_EXECUTE = 0x0020, // file
109 | FILE_TRAVERSE = 0x0020, // directory
110 |
111 | FILE_DELETE_CHILD = 0x0040, // directory
112 |
113 | FILE_READ_ATTRIBUTES = 0x0080, // all
114 |
115 | FILE_WRITE_ATTRIBUTES = 0x0100 // all
116 | }
117 |
118 | [Flags]
119 | public enum FileAttributes : uint
120 | {
121 | Readonly = 0x00000001,
122 | Hidden = 0x00000002,
123 | System = 0x00000004,
124 | Directory = 0x00000010,
125 | Archive = 0x00000020,
126 | Device = 0x00000040,
127 | Normal = 0x00000080,
128 | Temporary = 0x00000100,
129 | SparseFile = 0x00000200,
130 | ReparsePoint = 0x00000400,
131 | Compressed = 0x00000800,
132 | Offline = 0x00001000,
133 | NotContentIndexed = 0x00002000,
134 | Encrypted = 0x00004000,
135 | Write_Through = 0x80000000,
136 | Overlapped = 0x40000000,
137 | NoBuffering = 0x20000000,
138 | RandomAccess = 0x10000000,
139 | SequentialScan = 0x08000000,
140 | DeleteOnClose = 0x04000000,
141 | BackupSemantics = 0x02000000,
142 | PosixSemantics = 0x01000000,
143 | OpenReparsePoint = 0x00200000,
144 | OpenNoRecall = 0x00100000,
145 | FirstPipeInstance = 0x00080000
146 | }
147 |
148 | public enum FILE_INFORMATION_CLASS
149 | {
150 | FileDirectoryInformation = 1,
151 | FileFullDirectoryInformation = 2,
152 | FileBothDirectoryInformation = 3,
153 | FileBasicInformation = 4,
154 | FileStandardInformation = 5,
155 | FileInternalInformation = 6,
156 | FileEaInformation = 7,
157 | FileAccessInformation = 8,
158 | FileNameInformation = 9,
159 | FileRenameInformation = 10,
160 | FileLinkInformation = 11,
161 | FileNamesInformation = 12,
162 | FileDispositionInformation = 13,
163 | FilePositionInformation = 14,
164 | FileFullEaInformation = 15,
165 | FileModeInformation = 16,
166 | FileAlignmentInformation = 17,
167 | FileAllInformation = 18,
168 | FileAllocationInformation = 19,
169 | FileEndOfFileInformation = 20,
170 | FileAlternateNameInformation = 21,
171 | FileStreamInformation = 22,
172 | FilePipeInformation = 23,
173 | FilePipeLocalInformation = 24,
174 | FilePipeRemoteInformation = 25,
175 | FileMailslotQueryInformation = 26,
176 | FileMailslotSetInformation = 27,
177 | FileCompressionInformation = 28,
178 | FileObjectIdInformation = 29,
179 | FileCompletionInformation = 30,
180 | FileMoveClusterInformation = 31,
181 | FileQuotaInformation = 32,
182 | FileReparsePointInformation = 33,
183 | FileNetworkOpenInformation = 34,
184 | FileAttributeTagInformation = 35,
185 | FileTrackingInformation = 36,
186 | FileIdBothDirectoryInformation = 37,
187 | FileIdFullDirectoryInformation = 38,
188 | FileValidDataLengthInformation = 39,
189 | FileShortNameInformation = 40,
190 | FileIoCompletionNotificationInformation = 41,
191 | FileIoStatusBlockRangeInformation = 42,
192 | FileIoPriorityHintInformation = 43,
193 | FileSfioReserveInformation = 44,
194 | FileSfioVolumeInformation = 45,
195 | FileHardLinkInformation = 46,
196 | FileProcessIdsUsingFileInformation = 47,
197 | FileNormalizedNameInformation = 48,
198 | FileNetworkPhysicalNameInformation = 49,
199 | FileMaximumInformation = 50
200 | }
201 |
202 | [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
203 | public struct WIN32_FIND_DATAW
204 | {
205 | public FileAttributes dwFileAttributes;
206 | public System.Runtime.InteropServices.ComTypes.FILETIME ftCreationTime;
207 | public System.Runtime.InteropServices.ComTypes.FILETIME ftLastAccessTime;
208 | public System.Runtime.InteropServices.ComTypes.FILETIME ftLastWriteTime;
209 | public uint nFileSizeHigh; //changed all to uint, otherwise you run into unexpected overflow
210 | public uint nFileSizeLow; //|
211 | public uint dwReserved0; //|
212 | public uint dwReserved1; //v
213 | [MarshalAs(UnmanagedType.ByValTStr, SizeConst = MAX_PATH)]
214 | public string cFileName;
215 | [MarshalAs(UnmanagedType.ByValTStr, SizeConst = MAX_ALTERNATE)]
216 | public string cAlternate;
217 | }
218 |
219 | [StructLayout(LayoutKind.Sequential)]
220 | public struct FILE_DISPOSITION_INFORMATION
221 | {
222 | [MarshalAs(UnmanagedType.Bool)]
223 | public bool DeleteFile;
224 | }
225 |
226 | [StructLayout(LayoutKind.Sequential)]
227 | public struct IO_STATUS_BLOCK
228 | {
229 | public IntPtr Status;
230 | public IntPtr Information;
231 | }
232 |
233 | [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
234 | public struct LUID
235 | {
236 | internal uint LowPart;
237 | internal uint HighPart;
238 | }
239 |
240 | [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
241 | public struct LUID_AND_ATTRIBUTES
242 | {
243 | internal LUID Luid;
244 | internal uint Attributes;
245 | }
246 |
247 | [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
248 | public struct TOKEN_PRIVILEGE
249 | {
250 | internal uint PrivilegeCount;
251 | internal LUID_AND_ATTRIBUTES Privilege;
252 | }
253 |
254 | [DllImport("kernel32.dll")]
255 | public static extern IntPtr GetCurrentProcess();
256 |
257 | [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
258 | public static extern uint GetFullPathNameW([MarshalAs(UnmanagedType.LPWStr)]string lpFileName, int nBufferLength, StringBuilder lpBuffer, IntPtr mustBeZero);
259 |
260 | [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
261 | [return: MarshalAs(UnmanagedType.Bool)]
262 | public static extern bool DeleteFileW([MarshalAs(UnmanagedType.LPWStr)]string lpFileName);
263 |
264 | [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
265 | public static extern uint GetFileAttributesW([MarshalAs(UnmanagedType.LPWStr)]string lpFileName);
266 |
267 | [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
268 | public static extern bool SetFileAttributesW([MarshalAs(UnmanagedType.LPWStr)]string lpFileName, uint dwFileAttributes);
269 |
270 | [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
271 | public static extern FindFileSafeHandle FindFirstFileW([MarshalAs(UnmanagedType.LPWStr)]string lpFileName, out WIN32_FIND_DATAW lpFindFileData);
272 |
273 | [DllImport("kernel32", SetLastError = true, CharSet = CharSet.Unicode)]
274 | public static extern bool FindNextFileW(FindFileSafeHandle hFindFile, out WIN32_FIND_DATAW lpFindFileData);
275 |
276 | [DllImport("kernel32", SetLastError = true, CharSet = CharSet.Unicode)]
277 | public static extern bool FindClose(IntPtr hFindFile);
278 |
279 | [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
280 | public static extern bool RemoveDirectoryW([MarshalAs(UnmanagedType.LPWStr)]string lpPathName);
281 |
282 | [DllImport("Kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
283 | public static extern SafeFileHandle CreateFile(
284 | string fileName,
285 | EFileAccess fileAccess,
286 | [MarshalAs(UnmanagedType.U4)] FileShare fileShare,
287 | IntPtr securityAttributes,
288 | [MarshalAs(UnmanagedType.U4)] FileMode creationDisposition,
289 | int flags,
290 | IntPtr template);
291 |
292 | [DllImport("Kernel32.dll", SetLastError = true)]
293 | extern static bool CloseHandle(IntPtr handle);
294 |
295 | [DllImport("ntdll.dll", SetLastError = false)]
296 | public static extern int RtlNtStatusToDosError(int Status);
297 |
298 |
299 | [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Auto)]
300 | public static extern bool LookupPrivilegeValue(string lpSystemName, string lpName, out LUID lpLuid);
301 |
302 | [DllImport("ntdll.dll", ExactSpelling = true, SetLastError = false)]
303 | public static extern int NtSetInformationFile(
304 | SafeFileHandle FileHandle,
305 | ref IO_STATUS_BLOCK ioStatus,
306 | IntPtr FileInformation,
307 | Int32 Length,
308 | FILE_INFORMATION_CLASS fileClass);
309 |
310 | [DllImport("ADVAPI32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
311 | public static extern
312 | bool AdjustTokenPrivileges(
313 | [In] SafeAccessTokenHandle TokenHandle,
314 | [In] bool DisableAllPrivileges,
315 | [In] ref TOKEN_PRIVILEGE NewState,
316 | [In] uint BufferLength,
317 | [In] IntPtr PreviousState,
318 | [In] IntPtr ReturnLength);
319 |
320 | [DllImport("ADVAPI32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
321 | public static extern
322 | bool OpenProcessToken(
323 | [In] IntPtr ProcessToken,
324 | [In] TokenAccessLevels DesiredAccess,
325 | [Out] out SafeAccessTokenHandle TokenHandle);
326 | }
327 | }
328 |
--------------------------------------------------------------------------------