【问题标题】:UWP application unable to access USB drive even though permissions are set即使设置了权限,UWP 应用程序也无法访问 USB 驱动器
【发布时间】:2021-10-04 14:41:02
【问题描述】:

我正在开发一个应用程序,该应用程序负责格式化 USB 驱动器并准备将其进一步用于嵌入式系统。

我正在使用堆栈溢出时发现的以下方法格式化驱动器(不幸的是,我没有保存链接。如果我再次找到它,我会在那里发布)

public static bool FormatUSB(string driveLetter, string fileSystem = "FAT32", bool quickFormat = true,
                                   int clusterSize = 4096, string label = "USB_0000", bool enableCompression = false)
        {
            //add logic to format Usb drive
            //verify conditions for the letter format: driveLetter[0] must be letter. driveLetter[1] must be ":" and all the characters mustn't be more than 2
            if (driveLetter.Length != 2 || driveLetter[1] != ':' || !char.IsLetter(driveLetter[0]))
                return false;

            //query and format given drive 
            //best option is to use ManagementObjectSearcher

            var files = Directory.GetFiles(driveLetter);
            var directories = Directory.GetDirectories(driveLetter);

            foreach (var item in files)
            {
                try
                {
                    File.Delete(item);
                }
                catch (UnauthorizedAccessException) { }
                catch (IOException) { }
            }

            foreach (var item in directories)
            {
                try
                {
                    Directory.Delete(item);
                }
                catch (UnauthorizedAccessException) { }
                catch (IOException) { }
            }

            ManagementObjectSearcher searcher = new ManagementObjectSearcher(@"select * from Win32_Volume WHERE DriveLetter = '" + driveLetter + "'");
            foreach (ManagementObject vi in searcher.Get())
            {
                try
                {
                    var completed = false;
                    var watcher = new ManagementOperationObserver();

                    watcher.Completed += (sender, args) =>
                    {
                        Console.WriteLine("USB format completed " + args.Status);
                        completed = true;
                    };
                    watcher.Progress += (sender, args) =>
                    {
                        Console.WriteLine("USB format in progress " + args.Current);
                    };

                    vi.InvokeMethod(watcher, "Format", new object[] { fileSystem, quickFormat, clusterSize, label, enableCompression });

                    while (!completed) { System.Threading.Thread.Sleep(1000); }


                }
                catch
                {

                }
            }
            return true;
        }

我还添加了(我认为)在清单中访问可移动驱动器所需的所有功能:

<?xml version="1.0" encoding="utf-8"?>

<Package
  xmlns="http://schemas.microsoft.com/appx/manifest/foundation/windows10"
  xmlns:mp="http://schemas.microsoft.com/appx/2014/phone/manifest"
  xmlns:uap="http://schemas.microsoft.com/appx/manifest/uap/windows10"
  xmlns:rescap="http://schemas.microsoft.com/appx/manifest/foundation/windows10/restrictedcapabilities"
  xmlns:iot="http://schemas.microsoft.com/appx/manifest/iot/windows10"
  IgnorableNamespaces="uap mp rescap iot">

  <Identity
    Name="7b9becad-6afd-4872-bcb7-7f414c098edf"
    Publisher="CN=vitto"
    Version="1.0.0.0" />

  <mp:PhoneIdentity PhoneProductId="7b9becad-6afd-4872-bcb7-7f414c098edf" PhonePublisherId="00000000-0000-0000-0000-000000000000"/>

  <Properties>
    <DisplayName>DiskMakerApp</DisplayName>
    <PublisherDisplayName>vitto</PublisherDisplayName>
    <Logo>Assets\StoreLogo.png</Logo>
  </Properties>

  <Dependencies>
    <TargetDeviceFamily Name="Windows.Universal" MinVersion="10.0.0.0" MaxVersionTested="10.0.0.0" />
  </Dependencies>

  <Resources>
    <Resource Language="x-generate"/>
  </Resources>

  <Applications>
    <Application Id="App"
      Executable="$targetnametoken$.exe"
      EntryPoint="DiskMakerApp.App">
      <uap:VisualElements
        DisplayName="DiskMakerApp"
        Square150x150Logo="Assets\Square150x150Logo.png"
        Square44x44Logo="Assets\Square44x44Logo.png"
        Description="DiskMakerApp"
        BackgroundColor="transparent">
        <uap:DefaultTile Wide310x150Logo="Assets\Wide310x150Logo.png"/>
        <uap:SplashScreen Image="Assets\SplashScreen.png" />
      </uap:VisualElements>
    </Application>
  </Applications>

  <Capabilities>
      <rescap:Capability Name="broadFileSystemAccess" />
      <rescap:Capability Name="appCaptureSettings" />
      <Capability Name="internetClient" />
    <uap:Capability Name="removableStorage" />
      <iot:Capability Name="systemManagement"/>
      <DeviceCapability Name="usb"/>
  </Capabilities>
</Package>

并且还允许在 Window 的设置页面中访问文件系统:

但我仍然得到:

我想知道我是否遗漏了什么。有没有办法可以让我以管理员身份运行该应用程序^这能解决问题吗? (无论如何,只有管理员才能在现实生活场景中运行该应用程序)

【问题讨论】:

  • 为应用程序构建可执行文件,然后像你说的那样以管理员身份运行 - 这应该确认它是否是管理员权限问题
  • 另外,您是否可以通过资源管理器正常访问U盘以排除任何杂项。驱动器有问题?
  • 我以管理员身份运行 VS,它应该以管理员权限运行应用程序,但仍然出现错误),是的,我可以通过资源管理器访问驱动器。尝试直接从构建文件夹运行 .exe 不会做任何事情
  • 为 * 添加文件类型关联声明 - 是否有效?
  • 是的,根据文档,你是对的:docs.microsoft.com/en-us/uwp/schemas/appxpackage/…!没有更多错误但仍然被拒绝

标签: c# uwp access-denied removable-storage


【解决方案1】:

即使设置了权限,UWP 应用也无法访问 USB 驱动器

Directory.GetFiles 在 UWP 平台中不能不使用路径访问文件。并且只能使用 Windows Storage API 来访问带路径的文件(启用broadFileSystemAccess ),顺便提一下,System.Management Namespace 不适用于 UWP 平台,如果你想在里面格式化 USB 设备UWP 应用,请使用桌面扩展处理。更多信息请参考 stefan 的博客 UWP with Desktop Extension

【讨论】:

    猜你喜欢
    • 2018-03-08
    • 2017-03-17
    • 1970-01-01
    • 1970-01-01
    • 2020-06-19
    • 1970-01-01
    • 1970-01-01
    • 2016-05-28
    • 2023-04-01
    相关资源
    最近更新 更多