Невозможно получить доступ к библиотеке видео в UWP - PullRequest
0 голосов
/ 05 декабря 2018

Я чувствую, что что-то упустил, но не уверен, что это такое.

У меня есть два приложения UWP, которые я настроил для использования библиотеки видео в качестве места временного хранения.Одно приложение работает нормально, а другое говорит, что у него нет разрешения.Из того, что я могу сказать, кодировка точно такая же.Я проверил, что возможности приложения настроены одинаково в обоих приложениях.

Есть предложения, на что еще посмотреть?

Неработающий код:

public static async Task GetFileAsync()
        {
            var (authResult, message) = await Authentication.AquireTokenAsync();
            var httpClient = new HttpClient();
            HttpResponseMessage response;
            var request = new HttpRequestMessage(HttpMethod.Get, MainPage.fileurl);
            request.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", authResult.AccessToken);
            response = await httpClient.SendAsync(request);
            byte[] fileBytes = await response.Content.ReadAsByteArrayAsync();
            StorageLibrary videoLibrary = await StorageLibrary.GetLibraryAsync(KnownLibraryId.Videos);
            string saveFolder = videoLibrary.SaveFolder.Path;
            string saveFileName = App.Date + "-" + App.Shift + ".xlsx";
            saveLocation = saveFolder + "\\" + saveFileName;

            using (MemoryStream stream = new MemoryStream())
            {
                stream.Write(fileBytes, 0, (int)fileBytes.Length);
                using (spreadsheetDoc = SpreadsheetDocument.Open(stream, true))
                {
                    await Task.Run(() =>
                    {
                        File.WriteAllBytes(saveLocation, stream.ToArray());
                        return TaskStatus.RanToCompletion;
                    });
                }
            }
        }

        public async static Task UpdateCell(string docName, string text,
            uint rowIndex, string columnName)
        {
            StorageLibrary videoLibrary = await StorageLibrary.GetLibraryAsync(KnownLibraryId.Videos);
            string saveFolder = videoLibrary.SaveFolder.Path;
            string saveFileName = App.Date + "-" + App.Shift + ".xlsx";
            saveLocation = saveFolder + "\\" + saveFileName;

            await Task.Run(() =>
            {
                using (spreadsheetDoc = SpreadsheetDocument.Open(saveLocation, true))
                {
                    WorksheetPart worksheetPart =
                        GetWorksheetPartByName(spreadsheetDoc, "DC11Rounds");

                    if (worksheetPart != null)
                    {
                        Cell cell = GetCell(worksheetPart.Worksheet,
                                                    columnName, rowIndex);
                        cell.CellValue = new CellValue(text);
                        cell.DataType =
                            new EnumValue<CellValues>(CellValues.String);

                        worksheetPart.Worksheet.Save();
                    }
                }
                return TaskStatus.RanToCompletion;
            });
        }

Рабочий код:

public static async Task GetFileAsync()
        {
            var (authResult, message) = await Authentication.AquireTokenAsync();
            var httpClient = new HttpClient();
            HttpResponseMessage response;
            var request = new HttpRequestMessage(HttpMethod.Get, MainPage.fileurl);
            request.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", authResult.AccessToken);
            response = await httpClient.SendAsync(request);
            byte[] fileBytes = await response.Content.ReadAsByteArrayAsync();
            StorageLibrary videoLibrary = await StorageLibrary.GetLibraryAsync(KnownLibraryId.Videos);
            string saveFolder = videoLibrary.SaveFolder.Path;
            string saveFileName = App.Date + "-" + App.Shift + ".xlsx";
            saveLocation = saveFolder + "\\" + saveFileName;

            using (MemoryStream stream = new MemoryStream())
            {
                stream.Write(fileBytes, 0, (int)fileBytes.Length);
                using (spreadsheetDoc = SpreadsheetDocument.Open(stream, true))
                {
                    await Task.Run(() =>
                    {
                        File.WriteAllBytes(saveLocation, stream.ToArray());
                        return TaskStatus.RanToCompletion;
                    });
                }
            }
        }

        public async static Task UpdateCell(string docName, string text,
            uint rowIndex, string columnName)
        {
            StorageLibrary videoLibrary = await StorageLibrary.GetLibraryAsync(KnownLibraryId.Videos);
            string saveFolder = videoLibrary.SaveFolder.Path;
            string saveFileName = App.Date + "-" + App.Shift + ".xlsx";
            saveLocation = saveFolder + "\\" + saveFileName;

            await Task.Run(() =>
            {
                using (spreadsheetDoc = SpreadsheetDocument.Open(saveLocation, true))
                {
                    WorksheetPart worksheetPart =
                        GetWorksheetPartByName(spreadsheetDoc, "DC6Rounds");

                    if (worksheetPart != null)
                    {
                        Cell cell = GetCell(worksheetPart.Worksheet,
                                                    columnName, rowIndex);
                        cell.CellValue = new CellValue(text);
                        cell.DataType =
                            new EnumValue<CellValues>(CellValues.String);

                        worksheetPart.Worksheet.Save();
                    }
                }
                return TaskStatus.RanToCompletion;
            });
        }

Снимок экрана: enter image description here

Файл Appmanifast

<?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:iot="http://schemas.microsoft.com/appx/manifest/iot/windows10" xmlns:rescap="http://schemas.microsoft.com/appx/manifest/foundation/windows10/restrictedcapabilities"
  IgnorableNamespaces="uap mp iot rescap">
  <Identity Name="0724a480-5e3e-4cd4-a2a5-0c7305491ce3" Publisher="CN=tkrupka" Version="1.0.0.0" />
  <mp:PhoneIdentity PhoneProductId="0724a480-5e3e-4cd4-a2a5-0c7305491ce3" PhonePublisherId="00000000-0000-0000-0000-000000000000" />
  <Properties>
    <DisplayName>DC11Rounds</DisplayName>
    <PublisherDisplayName>tkrupka</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="DC11Rounds.App">
      <uap:VisualElements DisplayName="DC11Rounds" Square150x150Logo="Assets\Square150x150Logo.png" Square44x44Logo="Assets\Square44x44Logo.png" Description="DC11Rounds" BackgroundColor="transparent">
        <uap:DefaultTile Wide310x150Logo="Assets\Wide310x150Logo.png">
        </uap:DefaultTile>
        <uap:SplashScreen Image="Assets\SplashScreen.png" />
      </uap:VisualElements>
    </Application>
  </Applications>
  <Capabilities>
    <Capability Name="internetClient" />
    <Capability Name="privateNetworkClientServer" />
    <uap:Capability Name="enterpriseAuthentication" />
    <uap:Capability Name="videosLibrary" />
    <rescap:Capability Name="broadFileSystemAccess" />
  </Capabilities>
</Package>

Рабочий файл

<?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" IgnorableNamespaces="uap mp">
  <Identity Name="9e9838f0-1e60-482a-b922-189cc5e928f9" Publisher="CN=XXXXXX" Version="1.0.0.0" />
  <mp:PhoneIdentity PhoneProductId="9e9838f0-1e60-482a-b922-189cc5e928f9" PhonePublisherId="00000000-0000-0000-0000-000000000000" />
  <Properties>
    <DisplayName>DC6Rounds</DisplayName>
    <PublisherDisplayName>XXXXXX</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="DC6Rounds.App">
      <uap:VisualElements DisplayName="DC6Rounds" Square150x150Logo="Assets\Square150x150Logo.png" Square44x44Logo="Assets\Square44x44Logo.png" Description="DC6Rounds" BackgroundColor="black">
        <uap:DefaultTile Wide310x150Logo="Assets\Wide310x150Logo.png">
        </uap:DefaultTile>
        <uap:SplashScreen Image="Assets\SplashScreen.png" BackgroundColor="black" />
      </uap:VisualElements>
    </Application>
  </Applications>
  <Capabilities>
    <Capability Name="internetClient" />
    <Capability Name="privateNetworkClientServer" />
    <uap:Capability Name="enterpriseAuthentication" />
    <uap:Capability Name="videosLibrary" />
  </Capabilities>
</Package>

Получение этой ошибки при попытке добавить ограниченные возможности:

Код серьезности Описание Состояние подавления строки файла проекта Предупреждение Элемент 'Возможности' в пространстве имен 'http://schemas.microsoft.com/appx/manifest/foundation/windows10' имеет недопустимый дочерний элемент' Возможности 'в пространстве имен' http://schemas.microsoft.com/appx/manifest/foundation/windows10/restrictedcapabilities'. Списокожидаемые возможные элементы: 'CapabilityChoice' в пространстве имен 'http://schemas.microsoft.com/appx/manifest/foundation/windows10', а также' Capability 'в пространстве имен' http://schemas.microsoft.com/appx/manifest/uap/windows10', а также 'Capability' в пространстве имен 'http://schemas.microsoft.com/appx/manifest/foundation/windows10', а также'Capability 'в пространстве имен' http://schemas.microsoft.com/appx/manifest/uap/windows10/4', а также 'Capability' в пространстве имен 'http://schemas.microsoft.com/appx/manifest/uap/windows10/6', а также' Capability 'в пространстве имен' http://schemas.microsoft.com/appx/manifest/uap/windows10/7', а также 'Capability' в пространстве имен 'http://schemas.microsoft.com/appx/manifest/uap/windows10/3', а также' Capability 'в пространстве имен' http://schemas.microsoft.com/appx/manifest/uap/windows10/2', а также 'CustomCapabilityChoice' в пространстве имен 'http://schemas.microsoft.com/appx/manifest/foundation/windows10'а также 'CustomCapability' в пространстве имен 'http://schemas.microsoft.com/appx/manifest/uap/windows10/4', а также' Dev .... DC11Rounds C: \ Users \ XXXXXX \ GitVault \ DC11Rounds \ DC11Rounds \ DC11Rounds \ Package.appxmanifest 31

Пробовал это:

    //StorageLibrary storageLibrary = await StorageLibrary.GetLibraryAsync(KnownLibraryId.Documents);
    //string saveFolder = storageLibrary.SaveFolder.Path;
    StorageFolder saveFolder = Windows.ApplicationModel.Package.Current.InstalledLocation;

Получил это:

Сообщение = Не удалось найти часть пути 'C: \ Users \ XXXXXX\ GitVault \ DC11Rounds \ DC11Rounds \ DC11Rounds \ bin \ x86 \ Debug \ AppX \ Windows.Storage.StorageFolder \ 20181205-Days.xlsx '.

Понял, что сделал ошибку и забыл .path.Так что у меня все еще та же проблема.

Ответы [ 2 ]

0 голосов
/ 17 декабря 2018

Я добавил broadFileSystemAccess, использовал библиотеку документов, изменил мое минимальное целевое значение и внес редакционные изменения из-за изменения минимального целевого значения.Проект сейчас работает!Спасибо вам обоим.Не уверен, как пометить как ответ, так как большая часть этого в комментариях

0 голосов
/ 05 декабря 2018

Проверьте, не отключен ли доступ приложения к библиотеке видео в приложении Настройки .Перейдите к Пуск , Настройки , там выберите Конфиденциальность и Видео .Список приложений справа должен содержать ваше приложение, и вам необходимо проверить, установлен ли переключатель на Вкл. .

Apps in Settings Privacy

...