CreateFolderAsync() private method

private CreateFolderAsync ( [ desiredName ) : IAsyncOperation
desiredName [
return IAsyncOperation
Example #1
0
        public async void InitFolders()
        {
            _localFolder = Windows.Storage.ApplicationData.Current.LocalFolder;

            var folderName = "";

            try
            {
                folderName = "medium";
                if (Directory.Exists($"{_localFolder.Path}\\{folderName}"))
                {
                    _mediumFolder = await _localFolder.GetFolderAsync(folderName);
                }
                else
                {
                    _mediumFolder = await _localFolder.CreateFolderAsync(folderName);
                }

                folderName = "thumb";
                if (Directory.Exists($"{_localFolder.Path}\\{folderName}"))
                {
                    _thumbFolder = await _localFolder.GetFolderAsync(folderName);
                }
                else
                {
                    _thumbFolder = await _localFolder.CreateFolderAsync(folderName);
                }

                folderName = "original";
                if (Directory.Exists($"{_localFolder.Path}\\{folderName}"))
                {
                    _originalFolder = await _localFolder.GetFolderAsync(folderName);
                }
                else
                {
                    _originalFolder = await _localFolder.CreateFolderAsync(folderName);
                }

                folderName = "tile";
                if (Directory.Exists($"{_localFolder.Path}\\{folderName}"))
                {
                    _tileFolder = await _localFolder.GetFolderAsync(folderName);
                }
                else
                {
                    _tileFolder = await _localFolder.CreateFolderAsync(folderName);
                }
            }
            catch //(System.IO.FileNotFoundException ex)
            {
                //todo: what would ever cause this ??! need to work out how to handle this type of error
            }
        }
 /// <summary>
 /// 要下载调用这个方法
 /// </summary>
 /// <param name="url">下载的文件网址的来源</param>
 /// <returns></returns>
 public static async Task Start(string filename,string url,DownloadType type,StorageFolder folder=null)
 {
     try
     {
         Uri uri = new Uri(Uri.EscapeUriString(url), UriKind.RelativeOrAbsolute);
         BackgroundDownloader downloader = new BackgroundDownloader();
         if (folder==null)
         {
             folder = await KnownFolders.MusicLibrary.CreateFolderAsync("kgdownload", CreationCollisionOption.OpenIfExists);
             switch (type)
             {
                 case DownloadType.song:
                     folder = await folder.CreateFolderAsync("song", CreationCollisionOption.OpenIfExists);
                     downloader.TransferGroup = BackgroundTransferGroup.CreateGroup("song");
                     break;
                 case DownloadType.mv:
                     folder = await folder.CreateFolderAsync("mv", CreationCollisionOption.OpenIfExists);
                     downloader.TransferGroup = BackgroundTransferGroup.CreateGroup("mv");
                     break;
                 case DownloadType.other:
                     folder = await folder.CreateFolderAsync("other", CreationCollisionOption.OpenIfExists);
                     downloader.TransferGroup = BackgroundTransferGroup.CreateGroup("other");
                     break;
                 default:
                     break;
             }
         }else
         {
             downloader.TransferGroup = BackgroundTransferGroup.CreateGroup("other");
         }
         //string name = uri.ToString().Substring(uri.ToString().LastIndexOf("/"), uri.ToString().Length);
         string name = filename;
         StorageFile file = await folder.CreateFileAsync(name, CreationCollisionOption.GenerateUniqueName);
         downloader.FailureToastNotification = DownloadedToast.Done(filename, DownloadedToast.DownResult.Fa);
         downloader.SuccessToastNotification = DownloadedToast.Done(filename, DownloadedToast.DownResult.Su);
         var download = downloader.CreateDownload(new Uri(url), file);
         TransferModel transfer = new TransferModel();
         transfer.DownloadOperation = download;
         transfer.Source = download.RequestedUri.ToString();
         transfer.Destination = download.ResultFile.Path;
         transfer.BytesReceived = download.Progress.BytesReceived;
         transfer.TotalBytesToReceive = download.Progress.TotalBytesToReceive;
         transfer.Progress = 0;
         transfers.Add(transfer);
         Progress<DownloadOperation> progressCallback = new Progress<DownloadOperation>(DownloadProgress);
         download.StartAsync().AsTask(cancelToken.Token, progressCallback);
     }
     catch
     {
         await new MessageDialog("链接已失效!").ShowAsync();
     }
 }
Example #3
0
        public async static Task ExtractTarArchiveAsync( Stream archiveStream, StorageFolder destinationFolder )
        {
            using( TarReader reader = TarReader.Open( archiveStream ) )
            {
                while( reader.MoveToNextEntry() )
                {
                    if( !reader.Entry.IsDirectory )
                    {
                        using( var entryStream = reader.OpenEntryStream() )
                        {
                            string fileName = Path.GetFileName( reader.Entry.Key );
                            string folderName = Path.GetDirectoryName( reader.Entry.Key );

                            StorageFolder folder = destinationFolder;
                            if( string.IsNullOrWhiteSpace( folderName ) == false )
                            {
                                folder = await destinationFolder.CreateFolderAsync( folderName, CreationCollisionOption.OpenIfExists );
                            }

                            StorageFile file = await folder.CreateFileAsync( fileName, CreationCollisionOption.OpenIfExists );
                            using( Stream fileStream = await file.OpenStreamForWriteAsync().ConfigureAwait( false ) )
                            {
                                await entryStream.CopyToAsync( fileStream );
                            }
                        }
                    }
                }
            }
        }
 protected StorageCacheBase(StorageFolder sf, string cacheDirectory, ICacheGenerator cacheFileNameGenerator, long cacheMaxLifetimeInMillis = DefaultCacheMaxLifetimeInMillis)
 {
     if (sf == null)
     {
         throw new ArgumentNullException("isf");
     }
     if (string.IsNullOrEmpty(cacheDirectory))
     {
         throw new ArgumentException("cacheDirectory name could not be null or empty");
     }
     if (cacheDirectory.StartsWith("\\"))
     {
         throw new ArgumentException("cacheDirectory name shouldn't starts with double slashes: \\");
     }
     if (cacheFileNameGenerator == null)
     {
         throw new ArgumentNullException("cacheFileNameGenerator");
     }
     SF = sf;
     CacheDirectory = cacheDirectory;
     CacheFileNameGenerator = cacheFileNameGenerator;
     CacheMaxLifetimeInMillis = cacheMaxLifetimeInMillis;
     // Creating cache directory if it not exists
     SF.CreateFolderAsync(CacheDirectory).AsTask();
 }
        private async void InitProfiles()
        {
            var profileFolders = await _localFolder.CreateFolderAsync("Profiles", CreationCollisionOption.OpenIfExists);

            var Files = await profileFolders.GetFilesAsync(CommonFileQuery.OrderByName); //Getting Text files

            if (Files.Count == 0)
            {
                // there are noe profile files
                // create one
                _profile = new Profile();
                string json = JsonConvert.SerializeObject(_profile, Formatting.Indented);

                ProfileTextBox.Text = new StringBuilder(ProfileTextBox.Text)
                                      .Append(json + "\n")
                                      .ToString();
                var textFile = await profileFolders.CreateFileAsync("default.json");

                await FileIO.WriteTextAsync(textFile, json);

                Files = await profileFolders.GetFilesAsync(CommonFileQuery.OrderByName);
            }
            ProfilesComboBox.Items?.Clear();
            // there are profiles
            string str = "";

            foreach (StorageFile file in Files)
            {
                str = str + ", " + file.Name;
                ProfilesComboBox.Items?.Add(file.Name);
            }

            ProfileTextBox.Text = new StringBuilder(ProfileTextBox.Text)
                                  .Append("Profiles found:" + str + "\n")
                                  .ToString();

            //TODO may be save
            if (ProfilesComboBox.Items?.Count > 0)
            {
                ProfilesComboBox.SelectedIndex = 0;
            }

            SwitchProfile(true);
        }
Example #6
0
        async Task <StorageFile> GetStorageFile(string tag, byte[] byteArray, string fileName)
        {
            Windows.Storage.StorageFolder storageFolder = Windows.Storage.ApplicationData.Current.LocalFolder;

            var tmpFolder = await storageFolder.CreateFolderAsync($"tmp-{tag}", CreationCollisionOption.ReplaceExisting);

            Windows.Storage.StorageFile sampleFile = await tmpFolder.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting);

            await Windows.Storage.FileIO.WriteBytesAsync(sampleFile, byteArray);

            return(sampleFile);
        }
Example #7
0
    public async Task Init(string appname) {
      var devices = Windows.Storage.KnownFolders.RemovableDevices;
      var sdCards = await devices.GetFoldersAsync();
      if (sdCards.Count == 0) return;
      _SDCard = sdCards[0];
      string foldername = string.Format("{0}_Log", appname);
      _LogFolder = await _SDCard.CreateFolderAsync(foldername, CreationCollisionOption.OpenIfExists);

      _FileName = string.Format("{0:yyyy-MM-dd}.txt", DateTime.Now);
      _Stream = await _LogFolder.OpenStreamForWriteAsync(_FileName, CreationCollisionOption.OpenIfExists);

    }
Example #8
0
        private async Task <StorageFolder> OpenDataFolder()
        {
            // 寻找该文件夹中的文件
            Windows.Storage.StorageFolder storageFolder = ApplicationData.Current.LocalFolder;
            if (Directory.Exists(storageFolder.Path + "\\Data"))
            {
                return(await storageFolder.GetFolderAsync("Data"));
            }
            await storageFolder.CreateFolderAsync("Data");

            return(await storageFolder.GetFolderAsync("Data"));
        }
 internal async static Task MergeFolders(StorageFolder source, StorageFolder target)
 {
     foreach (StorageFile sourceFile in await source.GetFilesAsync())
     {
         await sourceFile.CopyAndReplaceAsync(await target.CreateFileAsync(sourceFile.Name, CreationCollisionOption.OpenIfExists));
     }
     
     foreach (StorageFolder sourceDirectory in await source.GetFoldersAsync())
     {
         StorageFolder nextTargetSubDir = await target.CreateFolderAsync(sourceDirectory.Name, CreationCollisionOption.OpenIfExists);
         await MergeFolders(sourceDirectory, nextTargetSubDir);
     }
 }
Example #10
0
 /// <summary> 
 /// Unzips ZipArchiveEntry asynchronously. 
 /// </summary> 
 /// <param name="entry">The entry which needs to be unzipped</param> 
 /// <param name="filePath">The entry's full name</param> 
 /// <param name="unzipFolder">The unzip folder</param> 
 /// <returns></returns> 
 public static async Task UnzipZipArchiveEntryAsync(ZipArchiveEntry entry, string filePath, StorageFolder unzipFolder)
 {
     if (IfPathContainDirectory(filePath))
     {
         // Create sub folder 
         string subFolderName = Path.GetDirectoryName(filePath);
         bool isSubFolderExist = await IfFolderExistsAsync(unzipFolder, subFolderName);
         StorageFolder subFolder;
         if (!isSubFolderExist)
         {
             // Create the sub folder. 
             subFolder =
                 await unzipFolder.CreateFolderAsync(subFolderName, CreationCollisionOption.ReplaceExisting);
         }
         else
         {
             // Just get the folder. 
             subFolder =
                 await unzipFolder.GetFolderAsync(subFolderName);
         }
         // All sub folders have been created. Just pass the file name to the Unzip function. 
         string newFilePath = Path.GetFileName(filePath);
         if (!string.IsNullOrEmpty(newFilePath))
         {
             // Unzip file iteratively. 
             await UnzipZipArchiveEntryAsync(entry, newFilePath, subFolder);
         }
     }
     else
     {
         // Read uncompressed contents 
         using (Stream entryStream = entry.Open())
         {
             byte[] buffer = new byte[entry.Length];
             entryStream.Read(buffer, 0, buffer.Length);
             // Create a file to store the contents 
             StorageFile uncompressedFile = await unzipFolder.CreateFileAsync
             (entry.Name, CreationCollisionOption.ReplaceExisting);
             // Store the contents 
             using (IRandomAccessStream uncompressedFileStream =
             await uncompressedFile.OpenAsync(FileAccessMode.ReadWrite))
             {
                 using (Stream outstream = uncompressedFileStream.AsStreamForWrite())
                 {
                     outstream.Write(buffer, 0, buffer.Length);
                     outstream.Flush();
                 }
             }
         }
     }
 }
Example #11
0
 private static async Task<StorageFolder> GetOrCreateSubFolder(StorageFolder pOutFolder, string pDirectoryName)
 {
     try
     {
         var folder = await pOutFolder.GetFolderAsync(pDirectoryName);
         if (folder != null)
             return folder;
     }
     catch (Exception)
     {
         
     }
     return await pOutFolder.CreateFolderAsync(pDirectoryName, CreationCollisionOption.ReplaceExisting);
 }
        private static async Task InflateEntryAsync(ZipArchiveEntry entry, StorageFolder destFolder, bool createSub = false)
        {
           
            string filePath = entry.FullName;

            if (!string.IsNullOrEmpty(filePath) && filePath.Contains("/") && !createSub)
            {
                // Create sub folder 
                string subFolderName = Path.GetDirectoryName(filePath);

                StorageFolder subFolder;

                // Create or return the sub folder. 
                subFolder = await destFolder.CreateFolderAsync(subFolderName, CreationCollisionOption.OpenIfExists);

                string newFilePath = Path.GetFileName(filePath);

                if (!string.IsNullOrEmpty(newFilePath))
                {
                    // Unzip file iteratively. 
                    await InflateEntryAsync(entry, subFolder, true);
                }
            }
            else
            {
                // Read uncompressed contents 
                using (Stream entryStream = entry.Open())
                {
                    byte[] buffer = new byte[entry.Length];
                    entryStream.Read(buffer, 0, buffer.Length);

                    // Create a file to store the contents 
                    StorageFile uncompressedFile = await destFolder.CreateFileAsync(entry.Name, CreationCollisionOption.ReplaceExisting);

                    // Store the contents 
                    using (IRandomAccessStream uncompressedFileStream = 
                        await uncompressedFile.OpenAsync(FileAccessMode.ReadWrite))
                    {
                        using (Stream outstream = uncompressedFileStream.AsStreamForWrite())
                        {
                            outstream.Write(buffer, 0, buffer.Length);
                            outstream.Flush();
                        }
                    }
                }
            }
        }
Example #13
0
        async public static void copyFolder(StorageFolder from, StorageFolder _to)
        {
            StorageFolder to = await _to.CreateFolderAsync(from.Name, CreationCollisionOption.OpenIfExists);
            IReadOnlyList<StorageFile> storageFiles = await from.GetFilesAsync();
            foreach (var storageFile in storageFiles)
            {
                await storageFile.CopyAsync(to, storageFile.Name, NameCollisionOption.ReplaceExisting);
            }

            //IReadOnlyList<StorageFolder> storageFolders = await from.GetFoldersAsync();
            var queryResult = from.CreateFolderQuery();
            IReadOnlyList<StorageFolder> storageFolders = await queryResult.GetFoldersAsync();
            foreach (var storageFolder in storageFolders)
            {
                copyFolder(storageFolder, to);
            }

        }
        public ImageFileCache(string name = null, StorageFolder folder = null)
        {
            if (string.IsNullOrEmpty(name))
            {
                name = TileImageLoader.DefaultCacheName;
            }

            if (folder == null)
            {
                folder = TileImageLoader.DefaultCacheFolder;
            }

            this.name = name;

            folder.CreateFolderAsync(name, CreationCollisionOption.OpenIfExists).Completed = (o, s) =>
            {
                rootFolder = o.GetResults();
                Debug.WriteLine("Created ImageFileCache in {0}.", rootFolder.Path);
            };
        }
        private async void InitializeLibrary()
        {
            var myMusic = await Windows.Storage.StorageLibrary.GetLibraryAsync
                              (Windows.Storage.KnownLibraryId.Music);

            Windows.Storage.StorageFolder saveMusicFolder = myMusic.SaveFolder;
            try
            {
                MediaManager.Instance.SaveFolder = await StorageFolder.GetFolderFromPathAsync(saveMusicFolder.Path + @"\naive_media");
            }
            catch (Exception e)
            {
                MediaManager.Instance.SaveFolder = await saveMusicFolder.CreateFolderAsync("naive_media");
            }
            MediaManager.Instance.PlayHistories  = _playHistories;
            MediaManager.Instance.CachedItems    = _cachedItems;
            MediaManager.Instance.CloudResources = new ObservableCollection <CloudResource>();
            MediaManager.Instance.MediaElement   = MediaElement;
            MediaManager.Instance.LoadCachedItems();
            LoadCloudResources();
        }
    /// <summary>
    /// Creates a directory into a specified <see cref="StorageFolder"/> by creating all missing <see cref="StorageFolder"/>
    /// </summary>
    /// <param name="storageFolder">the folder where the function has to check</param>
    /// <param name="path">the directory path</param>
    /// <returns>true in case of success. false otherwise</returns>
    public async Task<bool> CreateDirectory(StorageFolder storageFolder, string path)
    {
      using (await InstanceLock.LockAsync())
      {
        var isCreated = true;

        try
        {
          var folderNames = path.Split(new []{'/'}, StringSplitOptions.RemoveEmptyEntries).ToList();

          // Cleans ".." in uri
          while (folderNames.Any(f => f.Equals("..")) == true)
          {
            var index = folderNames.FindIndex(f => f.Equals(".."));
            if (index == 0)
            {
              throw new ArgumentException("Invalid specified path, can't access of the parent of the source folder.");
            }
            folderNames.RemoveRange(index - 1, 2);
          }

          // Creates all missing folders
          foreach(var folderName in folderNames)
          {
            storageFolder = await storageFolder.CreateFolderAsync(folderName, CreationCollisionOption.OpenIfExists);
          }
        }
        catch
        {
          isCreated = false;
        }

        return isCreated;
      }
    }
        // Extract files from a downloaded zip archive stream
        private async Task ExtractZipArchive(Stream zipStream, StorageFolder folder)
        {
            using (var zip = new ZipArchive(zipStream, ZipArchiveMode.Read))
            {
                foreach (var entry in zip.Entries)
                {
                    CurrentFileName = entry.FullName;

                    if (String.IsNullOrEmpty(entry.Name))
                    {
                        string dir = Path.GetDirectoryName(entry.FullName);
                        await folder.CreateFolderAsync(dir, CreationCollisionOption.ReplaceExisting);
                    }
                    else
                    {
                        await ExtractZipEntryAsync(entry, folder);
                    }
                }
            }
        }
Example #18
0
 private static async Task<StorageFolder> getInkingFolder(StorageFolder dataFolder)
 {
     StorageFolder inkingFolder = await dataFolder.CreateFolderAsync(INKING_FOLDER, CreationCollisionOption.OpenIfExists);
     return inkingFolder;
 }
Example #19
0
        /// <summary>
        /// Download a whole directory.
        /// </summary>
        private async void DownloadFTPDirectoryAsync(
            BackgroundDownloader downloader,
            NetworkCredential credential,
            FTPFileSystem item,
            StorageFolder targetFolder)
        {

            // List the sub folders and files.
            var subItems = await this.ListFtpContentAsync(item.Url, credential);

            // Download the sub folders and files.
            foreach (var subitem in subItems)
            {
                if (subitem.IsDirectory)
                {

                    // Create a local folder.
                    var subFolder = await targetFolder.CreateFolderAsync(subitem.Name,
                        CreationCollisionOption.ReplaceExisting);

                    // Download the whole folder.
                    DownloadFTPDirectoryAsync(downloader, credential, subitem, subFolder);
                }
                else
                {

                    // Create a local file.
                    var file = await targetFolder.CreateFileAsync(subitem.Name,
                        CreationCollisionOption.GenerateUniqueName);

                    // Download the file.
                    DownloadFTPFileAsync(downloader, credential, subitem, file);
                }
            }
        }
Example #20
0
        /// <summary>
        /// Download files, directories and their subdirectories.
        /// </summary>
        public async void DownloadFTPItemsAsync(IEnumerable<FTPFileSystem> itemsToDownload,
           StorageFolder targetFolder, NetworkCredential credential)
        {

            // Create a BackgroundDownloader
            BackgroundDownloader downloader = new BackgroundDownloader();

            // Download sub folders and files.
            foreach (var item in itemsToDownload.ToList())
            {
                if (item.IsDirectory)
                {

                    // Create a local folder.
                    var subFolder = await targetFolder.CreateFolderAsync(item.Name,
                        CreationCollisionOption.OpenIfExists);

                    // Download the whole folder.
                    DownloadFTPDirectoryAsync(downloader, credential, item, subFolder);
                }
                else
                {

                    // Create a local file.
                    var file = await targetFolder.CreateFileAsync(item.Name,
                        CreationCollisionOption.ReplaceExisting);

                    // Download the file.
                    DownloadFTPFileAsync(downloader, credential, item, file);
                }

            }
        }
Example #21
0
       private async void OpenComicCollection(StorageFolder chosenFolder, StorageFolder collections)
       {
           LoadingGridVisible(true);
           List<StorageFile> files = await RecursivelySearchForFiles(chosenFolder);
           StorageFolder collectionFolder = (StorageFolder)await collections.TryGetItemAsync(chosenFolder.Name);
           if (collectionFolder == null)
           {
               collectionFolder = await collections.CreateFolderAsync(chosenFolder.Name);
           }
           else
           {
               ShowWarning("Collection already exist!", "Adding new comics");
           }

           foreach (StorageFile sourceFile in files)
           {
               StorageFolder destFolder = (StorageFolder)await collectionFolder.TryGetItemAsync(sourceFile.Name);
               if (destFolder == null)
               {
                   destFolder = await collectionFolder.CreateFolderAsync(sourceFile.Name);
                   try
                   {
                       DefaultViewModel["LoadingFile"] = sourceFile.Name;
                       if (sourceFile.FileType.Equals("cbz") || sourceFile.FileType.Equals(".cbz"))
                           await FolderZip.UnZipFile(sourceFile, destFolder);
                       else if (sourceFile.FileType.Equals("cbr") || sourceFile.FileType.Equals(".cbr"))
                           await FolderZip.UnRarFile(sourceFile, destFolder);
                   }
                   catch (InvalidFormatException exception)
                   {
                       ShowWarning("Error opening file:" + sourceFile.Name, "Please try again");
                   }
               }
               LoadingBar.Value += (1.0 / files.Count()) * 100;
           }

           await CreateCollectionTiles();
           CollectionViews.Clear();
           foreach (CollectionTile tile in CollectionTiles)
           {
               CollectionViews.Add(new CollectionView(tile));
           }
           defaultViewModel["ComicTiles"] = ComicTiles;
           defaultViewModel["CollectionViews"] = CollectionViews;
           LoadingGridVisible(false);
       }
Example #22
0
        private async Task CopyFiles(StorageFolder pSource, StorageFolder pDestination)
        {
            foreach (var file in await pSource.GetFilesAsync())
                file.CopyAsync(pDestination);

            foreach (var folder in await pSource.GetFoldersAsync())
            {
                var newFolder = await pDestination.CreateFolderAsync(folder.Name);
                await CopyFiles(folder, newFolder);
            }
        }
Example #23
0
		public async Task<bool> ExportBinderAsync(string dbName, StorageFolder fromDirectory, StorageFolder toRootDirectory)
		{
			try
			{
				if (string.IsNullOrWhiteSpace(dbName) /*|| _dbNames?.Contains(dbName) == false */ || fromDirectory == null || toRootDirectory == null) return false;

				//var fromDirectory = await BindersDirectory
				//	.GetFolderAsync(dbName)
				//	.AsTask().ConfigureAwait(false);
				//if (fromDirectory == null) return false;

				//// what if you copy a directory to an existing one? Shouldn't you delete the contents first? No! But then, shouldn't you issue a warning?
				//var toDirectoryTest = await toRootDirectory.TryGetItemAsync(dbName).AsTask().ConfigureAwait(false);
				//if (toDirectoryTest != null)
				//{
				//	var confirmation = await UserConfirmationPopup.GetInstance().GetUserConfirmationBeforeExportingBinderAsync().ConfigureAwait(false);
				//	if (confirmation == null || confirmation.Item1 == false || confirmation.Item2 == false) return false;
				//}

				var toDirectory = await toRootDirectory
					.CreateFolderAsync(dbName, CreationCollisionOption.ReplaceExisting)
					.AsTask().ConfigureAwait(false);

				if (toDirectory == null) return false;

				Windows.Storage.AccessCache.StorageApplicationPermissions.FutureAccessList.AddOrReplace("PickedFolderToken", toDirectory);
				await fromDirectory.CopyDirContentsAsync(toDirectory, CancToken).ConfigureAwait(false);
				return true;
			}
			catch (OperationCanceledException) { }
			catch (Exception ex)
			{
				Logger.Add_TPL(ex.ToString(), Logger.FileErrorLogFilename);
			}
			return false;
		}
Example #24
0
 private async Task storage(StorageFolder folder)
 {
     if (string.IsNullOrEmpty(name))
     {
         string str = "请输入标题.md";
         file = await folder.CreateFileAsync(str, CreationCollisionOption.GenerateUniqueName);
         //name = file.Name;
         int n;
         n = name.IndexOf(".md");
         if (n > 0)
         {
             str = name.Substring(0, n);
         }
         this.folder = await folder.CreateFolderAsync(str, CreationCollisionOption.GenerateUniqueName);
     }
     else
     {
         if (name == "README.md")
         {
             this.folder = await folder.CreateFolderAsync("image", CreationCollisionOption.OpenIfExists);
         }
         else
         {
             this.folder = await folder.CreateFolderAsync(name, CreationCollisionOption.OpenIfExists);
         }
     }
 }
Example #25
0
 public async Task InitializeFolder(string userID)
 {
     UsersFolder = await ApplicationData.Current.LocalFolder.CreateFolderAsync("Users", CreationCollisionOption.OpenIfExists);
     PersonalFolder = await UsersFolder.CreateFolderAsync(userID, CreationCollisionOption.OpenIfExists);
 }
Example #26
0
 async void doInit(StorageFolder root, string directory) {
     folder = await root.CreateFolderAsync(directory, CreationCollisionOption.OpenIfExists);
 }
Example #27
0
        private async void PackageInstallDeploy()
        {
            if (PackageFile == null)
                return;


            //Clipboard "\\\\minwinpc\\c$" setText ??
            //Windows.ApplicationModel.DataTransfer.DataPackage dp = new Windows.ApplicationModel.DataTransfer.DataPackage();
            //dp.SetText("\\\\minwinpc\\c$");

            FolderPicker fp = new FolderPicker();
            fp.SuggestedStartLocation = PickerLocationId.ComputerFolder;
            fp.FileTypeFilter.Add("*");
            fp.CommitButtonText = "Select " + RemoteFileSystem.Text + " only.";
            RootRemoteCDrive = await fp.PickSingleFolderAsync();
            StorageFolder fldrRemotePackage = null;
            StorageFolder RemoteWindows = null;
            StorageFolder System32 = null;


            //Create or clean out remote folder
            try
            {
                fldrRemotePackage = await RootRemoteCDrive.CreateFolderAsync(InstallDir, CreationCollisionOption.OpenIfExists);

                if (fldrRemotePackage != null)
                {
                    var files = await fldrRemotePackage.GetFilesAsync();
                    foreach (StorageFile fi in files)
                        await fi.DeleteAsync();

                    RemoteWindows = await RootRemoteCDrive.GetFolderAsync("Windows");
                    if (RemoteWindows != null)
                    {
                        System32 = await RemoteWindows.GetFolderAsync("System32");
                    }
                }
                if ((fldrRemotePackage == null) || (System32 == null))
                    //Need a popup here
                    return;

            }
            catch (Exception ex)
            {
                //A folder not found
                string msg = ex.Message;
            }


            //Copy files to remote system
            StorageFolder fldrLocal = ApplicationData.Current.LocalFolder;
            try
            {
                var fldr = await fldrLocal.GetFolderAsync(PackageFile.Name);
                if (fldr != null)
                {
                    var files = await fldr.GetFilesAsync();
                    foreach (StorageFile fi in files)
                    {
                        if (fi.Name != "oemcustomization.cmd")
                            await fi.CopyAsync(fldrRemotePackage);
                        else
                            await fi.CopyAsync(System32, "oemcustomization.cmd", NameCollisionOption.ReplaceExisting);
                    }
                }
            }
            catch (Exception ex)
            {
                //Will be folder not found
                string msg = ex.Message;
            }

        }
        private async void Button_Click(object sender, RoutedEventArgs e)
        {
            Tot.Text = "";
            Vot.Text = "";
            Button button = sender as Button;

            button.IsEnabled = false;
            StorageFolder vere = imagefolder;
            StorageFolder hore = imagefolder;

            if (imgfiles == null)
            {
                return;
            }
            //Tot.Text = imagefile.Path;
            Tot.Text = imagefile.FileType;
            //若存在则获取,不存在则新建
            if (null == await imagefolder.TryGetItemAsync("Hor"))
            {
                hore = await imagefolder.CreateFolderAsync("Hor");
            }
            hore = await imagefolder.GetFolderAsync("Hor");

            if (await imagefolder.TryGetItemAsync("Ver") == null)
            {
                vere = await imagefolder.CreateFolderAsync("Ver");
            }
            vere = await imagefolder.GetFolderAsync("Ver");

            int    a = 0;
            int    b = 0;
            float  t = 0;
            float  p = 0;
            double c = 0;

            Tot.Text = a.ToString();
            Vot.Text = b.ToString();
            //Windows.Storage.StorageFolder imgfld = await imagefile.GetParentAsync();
            StorageApplicationPermissions.FutureAccessList.Add(imagefolder);
            IReadOnlyList <StorageFile> filelist = await imagefolder.GetFilesAsync();

            foreach (StorageFile file  in filelist)
            {
                progrb.Visibility = Visibility.Visible;
                p = filelist.Count;
                if (file.FileType == ".jpg" || file.FileType == ".png" || file.FileType == ".bmp")
                {
                    var varfil = await file.GetBasicPropertiesAsync();

                    if (varfil.Size == 0)
                    {
                        continue;
                    }
                    filename    = file.Name;
                    filename    = varfil.Size.ToString();
                    errtag.Text = filename;
                    ImageProperties imageProperties = await file.Properties.GetImagePropertiesAsync();

                    if (imageProperties.Width >= imageProperties.Height)
                    {
                        if (await hore.TryGetItemAsync(file.Name) != null)
                        {
                            continue;
                        }
                        inputstream = await file.OpenReadAsync();

                        await horbitmap.SetSourceAsync(inputstream);

                        HorImagePlace.Source = horbitmap;
                        await file.CopyAsync(hore);

                        a++;
                    }
                    else
                    {
                        if (await vere.TryGetItemAsync(file.Name) != null)
                        {
                            continue;
                        }
                        inputstream = await file.OpenReadAsync();

                        await verbitmap.SetSourceAsync(inputstream);

                        VerImagePlace.Visibility = Visibility.Visible;
                        VerImagePlace.Source     = verbitmap;
                        await file.CopyAsync(vere);

                        b++;
                    }
                    Tot.Text = a.ToString();
                    Vot.Text = b.ToString();
                }
                Tot.Text        += " Hor Pictures Copyed";
                Vot.Text        += " Ver Pictures Copyed";
                button.IsEnabled = true;
                btnOpn.IsEnabled = true;
                t++;
                c            = t / p;
                progrb.Value = c * 100;
            }
            StorageApplicationPermissions.FutureAccessList.Clear();
        }
Example #29
0
        async Task<bool> _createFolder(List<string> path, StorageFolder currentFolder)
        {
            if (path.Count == 0)
            {
                return false;
            }

            var current = path.FirstOrDefault();

            if (current == null)
            {
                return false;
            }

            path.RemoveAt(0);


            try
            {
                if (!await _folderExists(current, currentFolder))
                {
                    await currentFolder.CreateFolderAsync(current);
                }
            }
            catch { }


            if (path.Count == 0)
            {
                return await _folderExists(current, currentFolder);
            }

            return await _createFolder(path, await currentFolder.GetFolderAsync(current));
        }
        /// <summary>
        /// Сохраняет развертку в локальную папку
        /// </summary>
        /// <param name="data"></param>
        /// <param name="Tail"></param>
        /// <param name="time"></param>
        /// <param name="nameFile"></param>
        /// <returns></returns>
        public async Task saveAsync(int[,] data, int[,] Tail, string time, string nameFile, bool Taill)
        {
            string cul          = "en-US";
            var    folderPicker = new Windows.Storage.Pickers.FolderPicker();

            folderPicker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.Desktop;
            folderPicker.FileTypeFilter.Add("*");

            Windows.Storage.StorageFolder folder = await folderPicker.PickSingleFolderAsync();

            if (folder != null)
            {
                // Application now has read/write access to all contents in the picked folder
                // (including other sub-folder contents)
                Windows.Storage.AccessCache.StorageApplicationPermissions.
                FutureAccessList.AddOrReplace("PickedFolderToken", folder);
                StorageFolder storageFolderRazvertka = await folder.CreateFolderAsync("Развертка", CreationCollisionOption.OpenIfExists);

                StorageFile sampleFile = await storageFolderRazvertka.CreateFileAsync(nameFile + time + ".txt", CreationCollisionOption.ReplaceExisting);

                var stream = await sampleFile.OpenAsync(Windows.Storage.FileAccessMode.ReadWrite);

                using (var outputStream = stream.GetOutputStreamAt(0))
                {
                    using (var dataWriter = new Windows.Storage.Streams.DataWriter(outputStream))
                    {
                        string s = "i" + "\t" + "Ch1" + "\t" + "Ch2" + "\t" + "Ch3" + "\t" + "Ch4" + "\t" + "Ch5" + "\t" + "Ch6" + "\t" + "Ch7" + "\t" + "Ch8" + "\t" + "Ch9" + "\t" + "Ch10" + "\t" + "Ch11" + "\t" + "Ch12" + "\r\n";
                        for (int i = 0; i < 1024; i++)
                        {
                            s = s + (i + 1).ToString() + "\t";
                            for (int j = 0; j < 12; j++)
                            {
                                s = s + data[j, i] + "\t";
                            }
                            if (i < 1023)
                            {
                                s = s + "\r\n";
                            }
                            else
                            {
                            }
                        }
                        dataWriter.WriteString(s);
                        s = null;
                        await dataWriter.StoreAsync();

                        await outputStream.FlushAsync();
                    }
                }
                stream.Dispose(); // Or use the stream variable (see previous code snippet) with a using statement as well.
                if (Taill)
                {
                    // storageFolderRazvertka = await storageFolderRazvertka.CreateFolderAsync("Развертка", CreationCollisionOption.OpenIfExists);
                    sampleFile = await storageFolderRazvertka.CreateFileAsync(nameFile + time + "Хвост" + ".txt", CreationCollisionOption.ReplaceExisting);

                    stream = await sampleFile.OpenAsync(Windows.Storage.FileAccessMode.ReadWrite);

                    using (var outputStream = stream.GetOutputStreamAt(0))
                    {
                        using (var dataWriter = new Windows.Storage.Streams.DataWriter(outputStream))
                        {
                            string s = "i" + "\t" + "Ch1" + "\t" + "Ch2" + "\t" + "Ch3" + "\t" + "Ch4" + "\t" + "Ch5" + "\t" + "Ch6" + "\t" + "Ch7" + "\t" + "Ch8" + "\t" + "Ch9" + "\t" + "Ch10" + "\t" + "Ch11" + "\t" + "Ch12" + "\r\n";
                            for (int i = 0; i < 20000; i++)
                            {
                                s = s + (i + 1).ToString() + "\t";
                                for (int j = 0; j < 12; j++)
                                {
                                    s = s + Tail[j, i] + "\t";
                                }
                                if (i < 19999)
                                {
                                    s = s + "\r\n";
                                }
                                else
                                {
                                }

                                dataWriter.WriteString(s);
                                s = null;
                            }

                            await dataWriter.StoreAsync();

                            await outputStream.FlushAsync();
                        }
                    }
                    stream.Dispose();
                }
            }
        }
Example #31
0
        private async void Init()
        {
            await _local_folder.CreateFolderAsync("images_cache", CreationCollisionOption.OpenIfExists);

            await _local_folder.CreateFolderAsync("data_cache", CreationCollisionOption.OpenIfExists);
        }
Example #32
0
        /// <summary>
        /// Create a folder in the current rootFolder.
        /// </summary>
        /// <param name="folderName">Name of the folder to be created. This does not have to be an immediate sub-folder of the current folder.</param>
        /// <param name="rootFolder">The current folder.</param>
        /// <returns>None.</returns>
        public async Task<StorageFolder> CreateFolder(string folderName, StorageFolder rootFolder)
        {
            if (string.IsNullOrEmpty(folderName))
            {
                return rootFolder;
            }

            rootFolder = rootFolder ?? AntaresBaseFolder.Instance.RoamingFolder;
            folderName = NormalizePath(folderName);

            var startIndex = folderName.IndexOf('\\');

            if (startIndex == -1)
            {
                return await rootFolder.CreateFolderAsync(folderName, CreationCollisionOption.OpenIfExists);
            }

            rootFolder = await rootFolder.CreateFolderAsync(folderName.Substring(0, startIndex), CreationCollisionOption.OpenIfExists);
            folderName = folderName.Substring(startIndex + 1);
            return await CreateFolder(folderName, rootFolder);
        }
        /// <summary>
        /// Render ObjectDetector skill results
        /// </summary>
        /// <param name="frame"></param>
        /// <param name="objectDetections"></param>
        /// <returns></returns>
        private async Task DisplayFrameAndResultAsync(VideoFrame frame, int CCTVIndex)
        {
            await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, async() =>
            {
                try
                {
                    SoftwareBitmap savedBmp = null;
                    if (frame.SoftwareBitmap != null)
                    {
                        await m_processedBitmapSource[CCTVIndex].SetBitmapAsync(frame.SoftwareBitmap);
                        savedBmp = frame.SoftwareBitmap;
                    }
                    else
                    {
                        var bitmap = await SoftwareBitmap.CreateCopyFromSurfaceAsync(frame.Direct3DSurface, BitmapAlphaMode.Ignore);
                        await m_processedBitmapSource[CCTVIndex].SetBitmapAsync(bitmap);
                        savedBmp = bitmap;
                    }

                    // Retrieve and filter results if requested
                    IReadOnlyList <ObjectDetectorResult> objectDetections = m_binding.DetectedObjects;
                    if (m_objectKinds?.Count > 0)
                    {
                        objectDetections = objectDetections.Where(det => m_objectKinds.Contains(det.Kind)).ToList();
                    }
                    if (objectDetections != null)
                    {
                        // Update displayed results
                        m_bboxRenderer[CCTVIndex].Render(objectDetections);
                        bool PersonDetected = false;
                        int PersonCount     = 0;
                        var rects           = new List <Rect>();
                        foreach (var obj in objectDetections)
                        {
                            if (obj.Kind.ToString().ToLower() == "person")
                            {
                                PersonCount++;
                                PersonDetected = true;
                                rects.Add(obj.Rect);
                            }
                        }
                        if (PersonDetected)
                        {
                            bool KeepDistance = false;
                            if ((bool)ChkSocialDistancing.IsChecked)
                            {
                                //make sure there is more than 1 person
                                if (rects.Count > 1)
                                {
                                    var res = SocialDistanceHelpers.Detect(rects.ToArray());
                                    if (res.Result)
                                    {
                                        KeepDistance = true;
                                        m_bboxRenderer[CCTVIndex].DistanceLineRender(res.Lines);
                                        await speech.Read($"Please keep distance in {DataConfig.RoomName[CCTVIndex]}");
                                    }
                                }
                                else
                                {
                                    m_bboxRenderer[CCTVIndex].ClearLineDistance();
                                }
                            }
                            else
                            {
                                m_bboxRenderer[CCTVIndex].ClearLineDistance();
                            }
                            var msg = $"I saw {PersonCount} person in {DataConfig.RoomName[CCTVIndex]}";
                            if ((bool)ChkMode.IsChecked)
                            {
                                PlaySound(Sounds[Rnd.Next(0, Sounds.Count - 1)]);
                            }
                            else if (!KeepDistance)
                            {
                                await speech.Read(msg);
                            }
                            if ((bool)ChkPatrol.IsChecked)
                            {
                                await NotificationService.SendMail("Person Detected in BMSpace", msg, DataConfig.MailTo, DataConfig.MailFrom);
                                await NotificationService.SendSms(DataConfig.SmsTo, msg);
                            }
                            bool IsFaceDetected = false;
                            if ((bool)ChkDetectMask.IsChecked)
                            {
                                SoftwareBitmap softwareBitmapInput = frame.SoftwareBitmap;
                                // Retrieve a SoftwareBitmap to run face detection
                                if (softwareBitmapInput == null)
                                {
                                    if (frame.Direct3DSurface == null)
                                    {
                                        throw (new ArgumentNullException("An invalid input frame has been bound"));
                                    }
                                    softwareBitmapInput = await SoftwareBitmap.CreateCopyFromSurfaceAsync(frame.Direct3DSurface);
                                }
                                // We need to convert the image into a format that's compatible with FaceDetector.
                                // Gray8 should be a good type but verify it against FaceDetector’s supported formats.
                                const BitmapPixelFormat InputPixelFormat = BitmapPixelFormat.Gray8;
                                if (FaceDetector.IsBitmapPixelFormatSupported(InputPixelFormat))
                                {
                                    using (var detectorInput = SoftwareBitmap.Convert(softwareBitmapInput, InputPixelFormat))
                                    {
                                        // Run face detection and retrieve face detection result
                                        var faceDetectionResult = await m_faceDetector.DetectFacesAsync(detectorInput);

                                        // If a face is found, update face rectangle feature
                                        if (faceDetectionResult.Count > 0)
                                        {
                                            IsFaceDetected = true;
                                            // Retrieve the face bound and enlarge it by a factor of 1.5x while also ensuring clamping to frame dimensions
                                            BitmapBounds faceBound = faceDetectionResult[0].FaceBox;
                                            var additionalOffset   = faceBound.Width / 2;
                                            faceBound.X            = Math.Max(0, faceBound.X - additionalOffset);
                                            faceBound.Y            = Math.Max(0, faceBound.Y - additionalOffset);
                                            faceBound.Width        = (uint)Math.Min(faceBound.Width + 2 * additionalOffset, softwareBitmapInput.PixelWidth - faceBound.X);
                                            faceBound.Height       = (uint)Math.Min(faceBound.Height + 2 * additionalOffset, softwareBitmapInput.PixelHeight - faceBound.Y);

                                            var maskdetect  = await MaskDetect.PredictImageAsync(frame);
                                            var noMaskCount = maskdetect.Where(x => x.TagName == "no-mask").Count();
                                            if (noMaskCount > 0)
                                            {
                                                if (!KeepDistance)
                                                {
                                                    await speech.Read($"please wear a face mask in {DataConfig.RoomName[CCTVIndex]}");
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                            if (!IsFaceDetected)
                            {
                                m_bboxRenderer[CCTVIndex].ClearMaskLabel();
                            }
                            //save to picture libs

                            /*
                             * String path = Environment.GetFolderPath(Environment.SpecialFolder.MyPictures);
                             * path += "\\CCTV";
                             * if (!Directory.Exists(path))
                             * {
                             *  Directory.CreateDirectory(path);
                             * }*/
                            var TS = DateTime.Now - LastSaved[CCTVIndex];
                            if (savedBmp != null && TS.TotalSeconds > DataConfig.CaptureIntervalSecs && (bool)ChkCapture.IsChecked)
                            {
                                var myPictures = await Windows.Storage.StorageLibrary.GetLibraryAsync(Windows.Storage.KnownLibraryId.Pictures);
                                Windows.Storage.StorageFolder rootFolder    = myPictures.SaveFolder;
                                Windows.Storage.StorageFolder storageFolder = rootFolder;
                                var folderName = "cctv";
                                try
                                {
                                    storageFolder = await rootFolder.GetFolderAsync(folderName);
                                }
                                catch
                                {
                                    storageFolder = await rootFolder.CreateFolderAsync(folderName);
                                }
                                //if (Directory.Exists($"{rootFolder.Path}\\{folderName}"))
                                //else
                                // Create sample file; replace if exists.
                                //Windows.Storage.StorageFolder storageFolder = await Windows.Storage.StorageFolder.GetFolderFromPathAsync(path);
                                Windows.Storage.StorageFile sampleFile =
                                    await storageFolder.CreateFileAsync($"cctv_{DateTime.Now.ToString("dd_MM_yyyy_HH_mm_ss")}_{CCTVIndex}.jpg",
                                                                        Windows.Storage.CreationCollisionOption.ReplaceExisting);
                                ImageHelpers.SaveSoftwareBitmapToFile(savedBmp, sampleFile);
                                LastSaved[CCTVIndex] = DateTime.Now;
                            }
                        }
                    }

                    // Update the displayed performance text
                    StatusLbl.Text = $"bind: {m_bindTime.ToString("F2")}ms, eval: {m_evalTime.ToString("F2")}ms";
                }
                catch (TaskCanceledException)
                {
                    // no-op: we expect this exception when we change media sources
                    // and can safely ignore/continue
                }
                catch (Exception ex)
                {
                    NotifyUser($"Exception while rendering results: {ex.Message}");
                }
            });
        }
        private async Task<StorageFolder> CreateFolderToLocalStorageAsync(string path, StorageFolder folder)
        {
            string name;
            string[] list = ParseHelper.ParsePathAndName(path, ParseHelper.Mode.DIRECTORY, out name);

            foreach (string s in list)
            {
                folder = await folder.CreateFolderAsync(s, CreationCollisionOption.OpenIfExists);
            }
            return folder;
        }
Example #35
0
        public static async Task setSdFolder()
        {
            if(debug)
            {

            }
            sdFolder = (await Windows.Storage.KnownFolders.RemovableDevices.GetFoldersAsync() as IReadOnlyList<StorageFolder>).FirstOrDefault();
            if (sdFolder == null) return;
            fil = await (await sdFolder.CreateFolderAsync("Followshows", CreationCollisionOption.OpenIfExists)).CreateFileAsync("FollowshowsCrash.txt", CreationCollisionOption.OpenIfExists);
        }
        /// <summary>
        /// Private Methods & Testing Methods.
        /// </summary>
        private async Task<StorageFile> CreateFileToLocalStorageAsync(string path, StorageFolder folder)
        {
            string name;
            string[] list = ParseHelper.ParsePathAndName(path, ParseHelper.Mode.FULL_PATH, out name); // changed DIRECTORY to FULL_PATH

            foreach (string s in list)
            {
                folder = await folder.CreateFolderAsync(s, CreationCollisionOption.OpenIfExists);
            }
            return await folder.CreateFileAsync(name, CreationCollisionOption.OpenIfExists);
        }
    /// <summary>
    /// Creates a <see cref="StorageFolder"/> into a specified <see cref="StorageFolder"/>
    /// </summary>
    /// <param name="storageFolder">the folder where the function has to check</param>
    /// <param name="folderName">the folder name</param>
    /// <param name="creationOption">the <see cref="CreationCollisionOption"/></param>
    /// <returns>true in case of success. false otherwise</returns>
    public async Task<bool> CreateFolder(StorageFolder storageFolder, string folderName, CreationCollisionOption creationOption)
    {
      using (await InstanceLock.LockAsync())
      {
        var isCreated = true;

        try
        {
          folderName = folderName.Replace("/", "\\");
          var folder = await storageFolder.CreateFolderAsync(Path.GetDirectoryName(folderName), creationOption);
        }
        catch
        {
          isCreated = false;
        }

        return isCreated;
      }
    }
Example #38
0
 private static async Task<StorageFolder> _EnsureFolderExistsAsync(string name, StorageFolder parent)
 {
     if (parent == null) throw new ArgumentNullException(nameof(parent));
     return
         await
             parent.CreateFolderAsync(name, CreationCollisionOption.OpenIfExists).AsTask().ConfigureAwait(false);
 }
Example #39
-31
        public async void InitFolders()
        {
            _localFolder = Windows.Storage.ApplicationData.Current.LocalFolder;

            var folderName = "";
            try
            {
                folderName = "medium";
                if (Directory.Exists($"{_localFolder.Path}\\{folderName}")) _mediumFolder = await _localFolder.GetFolderAsync(folderName);
                else _mediumFolder = await _localFolder.CreateFolderAsync(folderName);

                folderName = "thumb";
                if (Directory.Exists($"{_localFolder.Path}\\{folderName}")) _thumbFolder = await _localFolder.GetFolderAsync(folderName);
                else _thumbFolder = await _localFolder.CreateFolderAsync(folderName);

                folderName = "original";
                if (Directory.Exists($"{_localFolder.Path}\\{folderName}")) _originalFolder = await _localFolder.GetFolderAsync(folderName);
                else _originalFolder = await _localFolder.CreateFolderAsync(folderName);

                folderName = "tile";
                if (Directory.Exists($"{_localFolder.Path}\\{folderName}")) _tileFolder = await _localFolder.GetFolderAsync(folderName);
                else _tileFolder = await _localFolder.CreateFolderAsync(folderName);

            }
            catch //(System.IO.FileNotFoundException ex)
            {
                //todo: what would ever cause this ??! need to work out how to handle this type of error
            }
            
        }