访问和创建/删除图片库中的文件?

时间:2017-07-31 17:39:07

标签: c# uwp isolatedstorage hololens

我正在尝试按照Microsofts UWP api中的说明在图片库中创建一个文件。

图片库通常具有以下路径 %USERPROFILE%\图片

我已在应用清单中启用了图片库功能。

像这样:

File.WriteAllBytes("%USERPROFILE%/Pictures", fileData);

它返回:

  

DirectoryNotFoundException:找不到路径的一部分' C:\ Data \ Users \ DefaultAccount \ AppData \ Local \ DevelopmentFiles \ HoloViewerVS.Debug_x86.jtth.jh \%USERPROFILE%\ Pictures'   `

当我尝试使用硬编码的用户名时,就像这样:

File.WriteAllBytes("jtth.jh/Pictures", fileData);

它返回相同的DirectoryNotFound异常:

  

DirectoryNotFoundException:找不到路径的一部分&#39; C:\ Data \ Users \ DefaultAccount \ AppData \ Local \ DevelopmentFiles \ HoloViewerVS.Debug_x86.jtth.jh \ jtth.jh \ Pictures&#39;`< / p>

那么,您如何访问图片库并将文件写入其中?显然,我必须在这里遗漏一些小东西,因为它试图访问图片库的路径在这里看起来很奇怪。

我看到它说如何获取图片库。&#39;使用StorageFolder:

public static StorageFolder PicturesLibrary { get; }

但我不确定如何将文件添加到此文件夹变量,就像我使用文件写入方式一样。

我可以按照我尝试的方式进行操作,还是需要跳过StorageFolder和/或async hoops?

澄清的例子:

        string imgName = currentFolderLoaded + "/" + temp.GetComponentInChildren<Text>().text;

        //example imgName to enhance clairty
imgName = C:\dev\Users\jtth\Hololens\ProjectFolder\App\HoloApp\Data\myFiles\pics\example.png

        //load image
        byte[] fileData;
        Texture2D tex = null;

        fileData = File.ReadAllBytes(imgName);
        tex = new Texture2D(2, 2);
        tex.LoadImage(fileData);

        //test hololens access
        //previous attempt -> File.WriteAllBytes("%USERPROFILE%/Pictures", fileData);
        //New attempt
        AsStorageFile(fileData, imgName);

        //Read Texture into RawImage component
        ImgObject.GetComponent<RawImage>().material.mainTexture = tex;

        //Enable component to render image in game
        ImgObject.GetComponent<RawImage>().enabled = true;

功能:

private static async Task<StorageFile> AsStorageFile(byte[] byteArray, string fileName)
{
    Windows.Storage.StorageFolder storageFolder = Windows.Storage.KnownFolders.PicturesLibrary;
    Windows.Storage.StorageFile sampleFile = await storageFolder.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting);
    await Windows.Storage.FileIO.WriteBytesAsync(sampleFile, byteArray);
    return sampleFile;
}

2 个答案:

答案 0 :(得分:1)

这是因为UWP应用程序在隔离存储下工作。与链接的MSDN文章中的第一个示例一样,请执行以下操作:

StorageFolder storageFolder = KnownFolders.PicturesLibrary;
StorageFile file = await storageFolder.CreateFileAsync("sample.png", CreationCollisionOption.ReplaceExisting);
// Do something with the new file.

普通的File.Xxx()调用将被隔离到您应用程序自己的小世界。

答案 1 :(得分:1)

  

我在运行此代码后检查Hololens上的照片应用程序并且它似乎没有创建图片?

如果您希望在Hololens的照片应用中显示您的照片,实际上您可能需要将照片保存到CameraRoll文件夹中。

但似乎无法直接保存,您可能需要移动图片文件作为解决方法。

var cameraRollFolder = Windows.Storage.KnownFolders.CameraRoll.Path;            
File.Move(_filePath, Path.Combine(cameraRollFolder, _filename));

详情请参阅此similar thread