tonwei139 发表于 2015-5-21 10:39:08

win8 app 创建文件夹目录

  一、在winrt里面创建一个指定的文件夹目录不太好弄呀。
  自己写一个吧。有更好的写法请多多指教我。
  代码部分:


///
    /// 在winrt隔离存储区创建目录
    ///
    public class ApplicationDataDirectory
    {
      ///
      /// 临时文件夹变量
      ///
      private static StorageFolder _TempFolder;
      ///
      /// 创建Winrt目录
      ///
      /// 目录[格式如 @"\a\b\c\d"]
      async public static Task CreateDirectory(string directory)
      {
            StorageFolder localFolder = ApplicationData.Current.LocalFolder;
         
            //每个文件夹的名称
            string[] folders = directory.Split(new string[] { @"\" }, StringSplitOptions.RemoveEmptyEntries);
         
            Queue folderList = new Queue();
            //将文件夹名放入一个集合中
            for (int i = 0; i < folders.Length; i++)
            {
                folderList.Enqueue(folders);
            }
            //创建第一个文件夹
            _TempFolder = await CreateFolder(localFolder, folderList.Peek());
            //此时将刚才已经创建的文件夹名移除
            folderList.Dequeue();
         
            //如果下面还有文件夹要创建
            if (folderList.Count >= 1)
            {
                //循环创建
                foreach (var folderName in folderList)
                {
                  _TempFolder = await CreateFolder(_TempFolder, folderName);
                }
            }
      }
      ///
      /// 在指定的文件夹下创建子文件夹
      ///
      /// 指定的文件夹
      /// 子文件夹名称
      ///
      async private static Task CreateFolder(StorageFolder parentFolder, string childFolderName)
      {
            //在指定的文件夹中创建子文件夹
            return await parentFolder.CreateFolderAsync(childFolderName, CreationCollisionOption.OpenIfExists);
      }
    }  
  比如我在 win8 metro 的隔离存储区创建一个文件目录\a\b\c\d
  此时的调用方法为:
  string path = @"\a\b\c\d";
  await ApplicationDataDirectory.CreateDirectory(path);
  
  
  
  
  二、上面写的太垃圾了,再修改下吧。


      async private void btnCreateDirectory(object sender, RoutedEventArgs args)
      {
            string directory = @"\a\b\c\d";
            await CreateFolder(directory);
      }
      async private Task CreateFolder(string directory)
      {
            StorageFolder tempStorageFolder=null;
            string[] folders = directory.Split(new string[] { @"\" }, StringSplitOptions.RemoveEmptyEntries);
            Queue _FolderList = new Queue();
            for (int i = 0; i < folders.Length; i++)
            {
                _FolderList.Enqueue(folders);
            }
            tempStorageFolder = ApplicationData.Current.LocalFolder;
            while (_FolderList.Count >= 1)
            {
                tempStorageFolder = await tempStorageFolder.CreateFolderAsync(_FolderList.Dequeue(), CreationCollisionOption.OpenIfExists);
            }
      }  
  欢迎有更好的写法!~
  

  
  http://files.iyunv.com/youhui/2012-11/FolderApp.rar
页: [1]
查看完整版本: win8 app 创建文件夹目录