如何使用Windows创建路径.存储API
本文关键字:存储 API 路径 创建 何使用 Windows | 更新日期: 2023-09-27 17:52:46
System.IO.CreateDirectory()
不能在。net上使用。
如何实现这个等效方法?StorageFolder.CreateFolderAsync()
在当前文件夹中创建子文件夹,但在我的情况下,我有一个类似的路径,并且需要创建该路径中不存在的所有文件夹。
没有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;
}
要在windows store应用的沙箱外创建文件夹,你必须在app-manifest中添加文档库,以及文件权限。
有关库和文档的更详细的解释,请参阅这个博客