-
-
Notifications
You must be signed in to change notification settings - Fork 2.8k
Expand file tree
/
Copy pathShellFolderExtensions.cs
More file actions
224 lines (175 loc) · 8.73 KB
/
Copy pathShellFolderExtensions.cs
File metadata and controls
224 lines (175 loc) · 8.73 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
// Copyright (c) Files Community
// Licensed under the MIT License.
using FluentFTP.Helpers;
using System.IO;
using System.Text;
using Vanara.PInvoke;
using Vanara.Windows.Shell;
namespace Files.App.Utils.Shell
{
/// <summary>
/// Provides static extension for shell folders.
/// </summary>
public static class ShellFolderExtensions
{
public static ShellLibraryItem GetShellLibraryItem(ShellLibraryEx library, string filePath)
{
var libraryItem = new ShellLibraryItem
{
FullPath = filePath,
AbsolutePath = library.GetDisplayName(ShellItemDisplayString.DesktopAbsoluteParsing),
RelativePath = library.GetDisplayName(ShellItemDisplayString.ParentRelativeParsing),
DisplayName = library.GetDisplayName(ShellItemDisplayString.NormalDisplay),
IsPinned = library.PinnedToNavigationPane,
};
var folders = library.Folders;
if (folders.Count > 0)
{
libraryItem.DefaultSaveFolder = SafetyExtensions.IgnoreExceptions(() => library.DefaultSaveFolder.FileSystemPath);
libraryItem.Folders = folders.Select(f => f.FileSystemPath).ToArray();
}
return libraryItem;
}
private static T TryGetProperty<T>(this ShellItemPropertyStore sip, Ole32.PROPERTYKEY key)
{
T value = default;
SafetyExtensions.IgnoreExceptions(() => sip.TryGetValue<T>(key, out value));
return value;
}
private static string? GetOriginalPathFromRecycleBinFile(string? physicalPath)
{
if (string.IsNullOrEmpty(physicalPath))
return null;
var fileNameFromPath = Path.GetFileName(physicalPath);
if (!fileNameFromPath.StartsWith("$R", StringComparison.OrdinalIgnoreCase) &&
!fileNameFromPath.StartsWith("$I", StringComparison.OrdinalIgnoreCase))
return null;
try
{
string directory = Path.GetDirectoryName(physicalPath)!;
string iFileName = fileNameFromPath.StartsWith("$R", StringComparison.OrdinalIgnoreCase) ?
"$I" + fileNameFromPath.RemovePrefix("$R") : fileNameFromPath.ToString();
string filePath = Path.Combine(directory, iFileName);
if (!File.Exists(filePath) && !Directory.Exists(filePath))
return null;
using var stream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
using var reader = new BinaryReader(stream, Encoding.Unicode);
// From the 24th to the 28th, contains the number of characters for the originalPath.
reader.BaseStream.Seek(24, SeekOrigin.Begin);
int pathCharCount = reader.ReadInt32();
// From the 28th byte, that's where the OriginalPath is.
// Windows is UTF-16, so each character takes 2 bytes, hence the multiplication.
byte[] pathBytes = reader.ReadBytes(pathCharCount * 2);
string originalPath = Encoding.Unicode.GetString(pathBytes).TrimEnd('\0');
return originalPath;
}
catch
{
}
return null;
}
public static ShellFileItem GetShellFileItem(ShellItem folderItem)
{
if (folderItem is null)
return null;
// NOTE: Do not use folderItem's Attributes property, throws unimplemented for some shell folders
// Zip archives are also shell folders, check for STREAM attribute
bool isFolder = folderItem.IsFolder && folderItem.IShellItem?.GetAttributes(Shell32.SFGAO.SFGAO_STREAM) is 0;
var parsingPath = folderItem.GetDisplayName(ShellItemDisplayString.DesktopAbsoluteParsing);
// True path on disk
parsingPath ??= folderItem.FileSystemPath;
string? recycleBinFileOriginalPath = GetOriginalPathFromRecycleBinFile(folderItem.FileSystemPath);
if (parsingPath is null || !Path.IsPathRooted(parsingPath))
{
parsingPath = parsingPath switch
{
"::{645FF040-5081-101B-9F08-00AA002F954E}" => Constants.UserEnvironmentPaths.RecycleBinPath,
"::{F02C1A0D-BE21-4350-88B0-7367FC96EF3C}" => Constants.UserEnvironmentPaths.NetworkFolderPath,
"::{208D2C60-3AEA-1069-A2D7-08002B30309D}" => Constants.UserEnvironmentPaths.NetworkFolderPath,
"::{20D04FE0-3AEA-1069-A2D8-08002B30309D}" => Constants.UserEnvironmentPaths.MyComputerPath,
"::{031E4825-7B94-4DC3-B131-E946B44C8DD5}\\Documents.library-ms" => ShellHelpers.GetLibraryFullPathFromShell(parsingPath),
"::{031E4825-7B94-4DC3-B131-E946B44C8DD5}\\Pictures.library-ms" => ShellHelpers.GetLibraryFullPathFromShell(parsingPath),
"::{031E4825-7B94-4DC3-B131-E946B44C8DD5}\\Music.library-ms" => ShellHelpers.GetLibraryFullPathFromShell(parsingPath),
"::{031E4825-7B94-4DC3-B131-E946B44C8DD5}\\Videos.library-ms" => ShellHelpers.GetLibraryFullPathFromShell(parsingPath),
// Use PIDL as path
// Replace "/" with "_" to avoid confusion with path separator
_ => $@"\\SHELL\{string.Join("\\", folderItem.PIDL.Select(x => x.GetBytes()).Select(x => Convert.ToBase64String(x, 0, x.Length).Replace('/', '_')))}"
};
}
var fileName = folderItem.Properties.TryGetProperty<string>(Ole32.PROPERTYKEY.System.ItemNameDisplay);
fileName ??= Path.GetFileName(folderItem.Name); // Original file name
fileName ??= folderItem.GetDisplayName(ShellItemDisplayString.ParentRelativeParsing);
var itemNameOrOriginalPath = folderItem.Name ?? fileName;
// In recycle bin "Name" contains original file path + name
string filePath = Path.IsPathRooted(itemNameOrOriginalPath) ?
itemNameOrOriginalPath : parsingPath;
if (!isFolder && !string.IsNullOrEmpty(parsingPath) && Path.GetExtension(parsingPath) is string realExtension && !string.IsNullOrEmpty(realExtension))
{
if (!string.IsNullOrEmpty(fileName) && !fileName.EndsWith(realExtension, StringComparison.OrdinalIgnoreCase))
fileName = $"{fileName}{realExtension}";
if (!string.IsNullOrEmpty(filePath) && !filePath.EndsWith(realExtension, StringComparison.OrdinalIgnoreCase))
filePath = $"{filePath}{realExtension}";
}
var fileTime = folderItem.Properties.TryGetProperty<System.Runtime.InteropServices.ComTypes.FILETIME?>(
Ole32.PROPERTYKEY.System.Recycle.DateDeleted);
var recycleDate = fileTime?.ToDateTime().ToLocalTime() ?? DateTime.Now; // This is LocalTime
fileTime = folderItem.Properties.TryGetProperty<System.Runtime.InteropServices.ComTypes.FILETIME?>(
Ole32.PROPERTYKEY.System.DateModified);
var modifiedDate = fileTime?.ToDateTime().ToLocalTime() ?? SafetyExtensions.IgnoreExceptions(() => folderItem.FileInfo?.LastWriteTime) ?? DateTime.Now; // This is LocalTime
fileTime = folderItem.Properties.TryGetProperty<System.Runtime.InteropServices.ComTypes.FILETIME?>(
Ole32.PROPERTYKEY.System.DateCreated);
var createdDate = fileTime?.ToDateTime().ToLocalTime() ?? SafetyExtensions.IgnoreExceptions(() => folderItem.FileInfo?.CreationTime) ?? DateTime.Now; // This is LocalTime
var fileSizeBytes = folderItem.Properties.TryGetProperty<ulong?>(Ole32.PROPERTYKEY.System.Size);
string fileSize = fileSizeBytes is not null ? folderItem.Properties.GetPropertyString(Ole32.PROPERTYKEY.System.Size) : null;
var fileType = folderItem.Properties.TryGetProperty<string>(Ole32.PROPERTYKEY.System.ItemTypeText);
string finalFilePath = string.IsNullOrEmpty(recycleBinFileOriginalPath) ? filePath : recycleBinFileOriginalPath;
return new(isFolder, parsingPath, fileName, finalFilePath, recycleDate, modifiedDate, createdDate, fileSize, fileSizeBytes ?? 0, fileType, folderItem.PIDL.GetBytes());
}
public static ShellLinkItem GetShellLinkItem(ShellLink linkItem)
{
if (linkItem is null)
return null;
var baseItem = GetShellFileItem(linkItem);
if (baseItem is null)
return null;
var link = new ShellLinkItem(baseItem)
{
IsFolder = !string.IsNullOrEmpty(linkItem.TargetPath) && linkItem.Target.IsFolder,
RunAsAdmin = linkItem.RunAsAdministrator,
ShowWindowCommand = (Windows.Win32.UI.WindowsAndMessaging.SHOW_WINDOW_CMD)linkItem.ShowState,
Arguments = linkItem.Arguments,
WorkingDirectory = Environment.ExpandEnvironmentVariables(linkItem.WorkingDirectory),
TargetPath = Environment.ExpandEnvironmentVariables(linkItem.TargetPath)
};
return link;
}
public static string GetParsingPath(this ShellItem item)
{
if (item is null)
return null;
return item.IsFileSystem ? item.FileSystemPath : item.ParsingName;
}
public static bool GetStringAsPIDL(string pathOrPIDL, out Shell32.PIDL pPIDL)
{
if (pathOrPIDL.StartsWith(@"\\SHELL\", StringComparison.Ordinal))
{
pPIDL = pathOrPIDL.Replace(@"\\SHELL\", "", StringComparison.Ordinal)
// Avoid confusion with path separator
.Replace('_', '/')
.Split('\\', StringSplitOptions.RemoveEmptyEntries)
.Select(pathSegment => new Shell32.PIDL(Convert.FromBase64String(pathSegment)))
.Aggregate(Shell32.PIDL.Combine);
return true;
}
else
{
pPIDL = Shell32.PIDL.Null;
return false;
}
}
public static ShellItem GetShellItemFromPathOrPIDL(string pathOrPIDL)
{
return GetStringAsPIDL(pathOrPIDL, out var pPIDL) ? ShellItem.Open(pPIDL) : ShellItem.Open(pathOrPIDL);
}
}
}