简体   繁体   中英

How to create a path using the Windows.Storage API?

System.IO.CreateDirectory() is not available on .NET for Windows Store Apps.

How can I implement this equivalent method? StorageFolder.CreateFolderAsync() creates a subfolder inside the current folder, but in my case I have a path like and need to create all folders that doesn't exist in this path.

The path is inside the app's sandbox in windows.

There's no API with exactly the same behaviour of System.IO.CreateDirectory() , so I implemented it using Windows.Storage classes:

    // Any and all directories specified in path are created, unless they already exist or unless 
    // some part of path is invalid. If the directory already exists, this method does not create a 
    // new directory.
    // The path parameter specifies a directory path, not a file path, and it must in 
    // the ApplicationData domain.
    // Trailing spaces are removed from the end of the path parameter before creating the directory.
    public static void CreateDirectory(string path)
    {
         path = path.Replace('/', '\\').TrimEnd('\\');
        StorageFolder folder = null;

        foreach(var f in new StorageFolder[] {
            ApplicationData.Current.LocalFolder, 
            ApplicationData.Current.RoamingFolder, 
            ApplicationData.Current.TemporaryFolder } )
        {
            string p = ParsePath(path, f);
            if (f != null)
            {
                path = p;
                folder = f;
                break;
            }
        }

        if(path == null)
            throw new NotSupportedException("This method implementation doesn't support " +
            "parameters outside paths accessible by ApplicationData.");

        string[] folderNames = path.Split('\\');
        for (int i = 0; i < folderNames.Length; i++)
        {
            var task = folder.CreateFolderAsync(folderNames[i], CreationCollisionOption.OpenIfExists).AsTask();
            task.Wait();
            if (task.Exception != null)
                throw task.Exception;
            folder = task.Result;
        }
    }

    private static string ParsePath(string path, StorageFolder folder)
    {
        if (path.Contains(folder.Path))
            {
                path = path.Substring(path.LastIndexOf(folder.Path) + folder.Path.Length + 1);
                return path;
            }
        return null;
    }

To create folders outside your app's sandbox in windows store app, you'll have to add the document library in app-manifest, along with file permissions.

For a much more detailed explanation regarding library and documents, Refer this blog

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM