System.IO.CreateDirectory()
。
如何实现此等效方法? StorageFolder.CreateFolderAsync()
在当前文件夹中创建一个子文件夹,但在我的情况下,我有一个类似的路径,需要创建此路径中不存在的所有文件夹。
该路径位于应用程序在Windows中的沙箱中。
答案 0 :(得分:4)
没有API与System.IO.CreateDirectory()
的行为完全相同,所以我使用Windows.Storage
类实现了它:
// 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;
}
答案 1 :(得分:0)
要在Windows应用商店应用的应用程序沙箱中创建文件夹,您必须在app-manifest中添加文档库以及文件权限。
有关库和文档的更详细说明,请参阅this博客