从网上搜索到一个powershell 代码,代码并不多,改写成c#使用com对象 Shell.Application
com对象 vba比较友好, 先用vba测试, 再改成c#
[C#] 纯文本查看 复制代码 void Main()
{
var shellobj = new shellObjectClass();
shellobj.Run();
}
class shellObjectClass
{
//ShellSpecialFolderConstants
//https://docs.microsoft.com/en-us/windows/win32/api/shldisp/ne-shldisp-shellspecialfolderconstants
const int ssfDRIVES = 0x11;
//MTP WPD Storage GUID
//https://docs.microsoft.com/en-us/uwp/api/Windows.Devices.Portable
const string wpdGuid = "6AC27878-A6FA-4155-BA85-F98F491D4F33";
public string dstPath { get; set; } = @"f:\dcim";
public void Run()
{
try
{
//MTP存储设备路径
var rootPath = GetRootPath();
foreach (var path in rootPath)
{
//MTP存储设备目录
var folderItems = GetFolderItems(path);
//多级路径
while (folderItems.Count == 1)
{
folderItems = folderItems.item[0].GetFolder.Items;
}
//照片文件夹
foreach (var item in folderItems)
{
if (item.Name == "DCIM") { folderItems = item.GetFolder.Items; break; }
}
//子文件夹
foreach (var item in folderItems)
{
if (item.Name == "Camera") { folderItems = item.GetFolder.Items; break; }
}
//文件筛选
foreach (var item in folderItems)
{
if (item.Name.Contains(".jpg")) { FileCopy(item, dstPath); }
}
//释放对象
folderItems = null;
}
}
catch (Exception ex)
{
Debug.WriteLine(ex);
}
}
private string[] GetRootPath()
{
var pathList = new List<string>();
try
{
Type shellType = Type.GetTypeFromProgID("Shell.Application");
dynamic shellObject = System.Activator.CreateInstance(shellType);
var objFolder = shellObject.NameSpace(ssfDRIVES).items;
foreach (var item in objFolder)
{
string path = item.Path;
if (Regex.Match(path, wpdGuid, RegexOptions.IgnoreCase).Success)
{
Console.WriteLine($"{item.Name},{item.Type},{item.Path}");
pathList.Add(path);
}
}
shellObject = null;
}
catch (Exception ex)
{
Debug.WriteLine(ex);
}
return pathList.ToArray();
}
private dynamic GetFolderItems(string path)
{
try
{
Type shellType = Type.GetTypeFromProgID("Shell.Application");
dynamic shellObject = System.Activator.CreateInstance(shellType);
return shellObject.NameSpace(path).items;
}
catch (Exception ex)
{
Debug.WriteLine(ex);
return new object[0];
}
}
private void FileCopy(dynamic srcItem, string dst)
{
//Folder.CopyHere method
//https://docs.microsoft.com/en-us/windows/win32/shell/folder-copyhere
try
{
Type shellType = Type.GetTypeFromProgID("Shell.Application");
dynamic shellObject = System.Activator.CreateInstance(shellType);
var dstObj = shellObject.NameSpace(dst);
Console.WriteLine(srcItem.Name);
dstObj.CopyHere(srcItem, 8); //参数无效?
}
catch (Exception ex)
{
Debug.WriteLine(ex);
}
}
} |