GetFolderAsync() public method

public GetFolderAsync ( [ name ) : IAsyncOperation
name [
return IAsyncOperation
Beispiel #1
0
        public async Task DeleteCacheFile()
        {
            try
            {
                StorageFolder folder = await _local_folder.GetFolderAsync("images_cache");

                if (folder != null)
                {
                    IReadOnlyCollection <StorageFile> files = await folder.GetFilesAsync(Windows.Storage.Search.CommonFileQuery.DefaultQuery);

                    //files.ToList().ForEach(async (f) => await f.DeleteAsync(StorageDeleteOption.PermanentDelete));
                    List <IAsyncAction> list = new List <IAsyncAction>();
                    foreach (var f in files)
                    {
                        list.Add(f.DeleteAsync(StorageDeleteOption.PermanentDelete));
                    }
                    List <Task> list2 = new List <Task>();
                    list.ForEach((t) => list2.Add(t.AsTask()));

                    await Task.Run(() => { Task.WaitAll(list2.ToArray()); });
                }
            }
            catch
            {
            }
        }
Beispiel #2
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
            }
        }
Beispiel #3
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"));
        }
    public async Task <string> configJson(string jsonFile, bool useBackup)
    {
        //try to load file from a user-accessible location
        //store config.json in LocalState oF the deployed app: http://127.0.0.1:10080/FileExplorer.htm
        Windows.Storage.StorageFolder storageFolder = Windows.Storage.ApplicationData.Current.LocalFolder;
        Windows.Storage.StorageFile   configFile    = null;
        try
        {
            configFile = await storageFolder.GetFileAsync(jsonFile);
        }
        catch (FileNotFoundException) {}

        if (configFile != null)
        {
            Debug.Log("[NetworkStartLogic:configJson] loading config from AppData");
        }
        else if (useBackup)
        {
            //fall back to a built-in config
            storageFolder = Windows.ApplicationModel.Package.Current.InstalledLocation;
            try
            {
                Windows.Storage.StorageFolder assetsFolder = await storageFolder.GetFolderAsync("assets");

                configFile = await assetsFolder.GetFileAsync(jsonFile);
            } catch (FileNotFoundException) {
                return(null);
            }

            if (configFile != null)
            {
                Debug.Log("[NetworkStartLogic:configJson] loading config from installation directory");
            }
        }

        if (configFile != null)
        {
            try
            {
                var buffer = await Windows.Storage.FileIO.ReadBufferAsync(configFile);

                using (var dataReader = Windows.Storage.Streams.DataReader.FromBuffer(buffer))
                {
                    string text = dataReader.ReadString(buffer.Length);
                    Debug.Log("[NetworkStartLogic:configJson] config.json reads: " + text);
                    return(text);
                }
            }
            catch (Exception e)
            {
                Debug.LogError("[NetworkStartLogic:configJson] Error reading config.json");
                return("");
            }
        }
        else
        {
            return(null);
        }
    }
 public static async Task<bool> AddDownload(string filename, string url, DownloadType type, StorageFolder folder = null)
 {
     try
     {
         var down = new BackgroundDownloader();
         down.TransferGroup = BackgroundTransferGroup.CreateGroup("other");
         if (folder == null)
         {
             folder = await KnownFolders.MusicLibrary.GetFolderAsync("kgdownload");
             switch (type)
             {
                 case DownloadType.song:
                     folder = await folder.GetFolderAsync("song");
                     down.TransferGroup = BackgroundTransferGroup.CreateGroup("song");
                     break;
                 case DownloadType.mv:
                     folder = await folder.GetFolderAsync("mv");
                     down.TransferGroup = BackgroundTransferGroup.CreateGroup("mv");
                     break;
                 case DownloadType.other:
                     folder = await folder.GetFolderAsync("other");
                     down.TransferGroup = BackgroundTransferGroup.CreateGroup("other");
                     break;
                 default:
                     break;
             }
         }
         var files= (await folder.GetFilesAsync()).ToList();
         foreach (var item in files)
         {
             await item.DeleteAsync();
         }
         var file = await folder.CreateFileAsync(filename);
         down.FailureToastNotification = DownloadToast(filename, DownloadResult.Failure);
         down.SuccessToastNotification = DownloadToast(filename, DownloadResult.Success);
         var opera= down.CreateDownload(new Uri(url), file);
         opera.CostPolicy = BackgroundTransferCostPolicy.Always;
         opera.StartAsync();
         return true;
     }
     catch (Exception)
     {
         return false;
     }
 }
Beispiel #6
0
        private async void LoadEntriesByDate()
        {
            EntriesListView.Items.Add(MainCalendar.SelectedDates[0].ToString());
            String ymfolder = YMDDate.Substring(0, 7);

            if (Directory.Exists(Path.Combine(appHomeFolder.Path, ymfolder)))
            {
                String[] allCurrentFiles = Directory.GetFiles(
                    Path.Combine(appHomeFolder.Path, ymfolder),
                    String.Format("{0}*.rtf", YMDDate),
                    SearchOption.TopDirectoryOnly);
                if (allCurrentFiles.Length > 0)
                {
                    StorageFolder subStorage = await appHomeFolder.GetFolderAsync(ymfolder);

                    Windows.Storage.StorageFile currentFile =
                        await subStorage.GetFileAsync(Path.GetFileName(allCurrentFiles[0]));

                    Stream s = await currentFile.OpenStreamForReadAsync();

                    MainRichEdit.Document.LoadFromStream(Windows.UI.Text.TextSetOptions.FormatRtf,
                                                         s.AsRandomAccessStream());
                    s.Dispose();
                    allCurrentFiles = allCurrentFiles.Skip(1).ToArray();

                    foreach (String f in allCurrentFiles)
                    {
                        PivotItem pi        = new PivotItem();
                        var       entryText = String.Format("Entry{0}", rootPivot.Items.Count + 1);

                        pi.Header = entryText;

                        RichEditBox reb = new RichEditBox();
                        reb.HorizontalAlignment = HorizontalAlignment.Stretch;
                        reb.VerticalAlignment   = VerticalAlignment.Stretch;

                        currentJournalEntries.Add(
                            new JournalEntry(reb,
                                             Path.Combine(appHomeFolder.Path),
                                             YMDDate, entryText));

                        pi.Content = reb;
                        pi.Loaded += PivotItem_Loaded;
                        rootPivot.Items.Add(pi);

                        rootPivot.SelectedIndex = 0;
                    }
                }
            }
            else
            {
                AddDefaultEntry();
            }
        }
        //-------------------------------------------------------------------------------
        #region +[static]copyToLocal 選択フォルダからローカルへコピー
        //-------------------------------------------------------------------------------
        //
        public async static void copyToLocal(StorageFolder rootDir, Action<int, int, int, int> progressReportFunc = null) {
            var localDir = Windows.Storage.ApplicationData.Current.LocalFolder;
            var dataDir_dst = await localDir.CreateFolderAsync(DATA_FOLDER_NAME, CreationCollisionOption.OpenIfExists);
            var dataDir_src = await rootDir.GetFolderAsync("CDATA");

            var fileList = await dataDir_src.GetFilesAsync(Windows.Storage.Search.CommonFileQuery.DefaultQuery);

            if (progressReportFunc != null) { progressReportFunc(0, 2, 0, fileList.Count); }

            int count = 0;
            foreach (var file in fileList) {
                await file.CopyAsync(dataDir_dst, file.Name, NameCollisionOption.ReplaceExisting);
                count++;
                if (progressReportFunc != null) { progressReportFunc(0, 2, count, fileList.Count); }
            }

            var imageDir = await localDir.CreateFolderAsync(IMAGES_FOLDER_NAME, CreationCollisionOption.OpenIfExists);

            var imgFile = await rootDir.GetFileAsync("C084CUTL.CCZ");
            MemoryStream ms = new MemoryStream();
            using (Stream stream = (await imgFile.OpenReadAsync()).AsStream()) {
                byte[] buf = new byte[0x10000000];
                while (true) {
                    int r = stream.Read(buf, 0, buf.Length);
                    if (r <= 0) { break; }
                    ms.Write(buf, 0, r);
                }
            }
            var zipArchive = new ZipArchive(ms);

            if (progressReportFunc != null) { progressReportFunc(1, 2, 0, zipArchive.Entries.Count); }
            count = 0;

            foreach (var entry in zipArchive.Entries) {
                string name = entry.Name;
                using (Stream dstStr = await imageDir.OpenStreamForWriteAsync(name, CreationCollisionOption.ReplaceExisting))
                using (Stream srcStr = entry.Open()) {
                    int size;
                    const int BUF_SIZE = 0x100000;
                    byte[] buf = new byte[BUF_SIZE];
                    size = srcStr.Read(buf, 0, BUF_SIZE);
                    while (size > 0) {
                        dstStr.Write(buf, 0, size);
                        size = srcStr.Read(buf, 0, BUF_SIZE);
                    }
                    count++;
                    if (progressReportFunc != null) { progressReportFunc(1, 2, count, zipArchive.Entries.Count); }
                }
            }
            if (progressReportFunc != null) { progressReportFunc(2, 2, count, zipArchive.Entries.Count); }

            ms.Dispose();
            zipArchive.Dispose();
        }
Beispiel #8
0
 // Working
 /// <summary>
 /// Gets a folder from the file system.
 /// </summary>
 /// <param name="folder">The folder that contains the folder.</param>
 /// <param name="folderName">Name of the folder.</param>
 /// <returns>The folder if it exists, null otherwise.</returns>
 public static StorageFolder GetFolder(StorageFolder folder, string folderName)
 {
     try
     {
         return folder.GetFolderAsync(folderName).AsTask().Result;
     }
     catch (Exception)
     {
         return null;
     }
 }
        /// <summary>
        /// check file system
        /// </summary>
        /// <param name="rootFolder"></param>
        private async Task checkFileSystem(StorageFolder rootFolder)
        {
            try
            {
                StorageFile metaFile = await rootFolder.GetFileAsync(CoreDriver.META_DATA);
                StorageFolder mdFolder = await rootFolder.GetFolderAsync(
                    MasterDataManagement.MASTER_DATA_FOLDER);
                StorageFolder transFolder = await rootFolder.GetFolderAsync(
                   TransactionDataManagement.TRANSACTION_DATA_FOLDER);

                IReadOnlyList<StorageFile> files = await mdFolder.GetFilesAsync();
                Assert.AreEqual(Enum.GetValues(typeof(MasterDataType)).Length, files.Count);

                files = await transFolder.GetFilesAsync();
                Assert.AreEqual(1, files.Count);
            }
            catch (Exception e)
            {
                Assert.Fail(e.ToString());
            }
        }
 /// <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();
                 }
             }
         }
     }
 }
Beispiel #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);
 }
Beispiel #12
0
        private async void LoadFileFromStorage(String ymfolder,
                                               String entryFileName,
                                               RichEditBox reb)
        {
            StorageFolder subStorage = await appHomeFolder.GetFolderAsync(ymfolder);

            Windows.Storage.StorageFile currentFile =
                await subStorage.GetFileAsync(entryFileName);

            Stream s = await currentFile.OpenStreamForReadAsync();

            reb.Document.LoadFromStream(Windows.UI.Text.TextSetOptions.FormatRtf,
                                        s.AsRandomAccessStream());
            s.Dispose();
        }
        public async Task ReadCsvFile(StorageFolder folder, string filename)
        {
            // assuming a folder named Data exists
            var folderContents = await folder.GetFolderAsync("Data");

            var file = await folderContents.GetFileAsync(filename);
            IList<string> content = await Windows.Storage.FileIO.ReadLinesAsync(file);

            string headings = content[0];
            _columnHeadings = headings.Split(',');

            for (int i = 1; i < content.Count; i++)
            {
                string line = content[i];
                string[] csvLine = line.Split(',');
                _dataset.Add(csvLine);
            }
        }
Beispiel #14
0
        async void GetSongs()
        {
            Windows.Storage.StorageFolder fsongs = Windows.Storage.KnownFolders.MusicLibrary;
            Windows.Storage.StorageFolder fhorn  = await fsongs.GetFolderAsync("Horn");

            horn = MediaSource.CreateFromStorageFile(await fhorn.GetFileAsync("horn.mp3"));



            var songs = await fsongs.GetFilesAsync();

            songscount = songs.Count;
            sources    = new MediaSource[songscount];
            int i = 0;

            foreach (var song in songs)
            {
                sources[i] = MediaSource.CreateFromStorageFile(song);
                await sources[i++].OpenAsync();
            }
        }
        /// <summary>
        /// Deletes folder.
        /// </summary>
        /// <param name="folderPath">Folder to be deleted.</param>
        /// <param name="rootFolder">Parental Folder contains to-be-deleted folder.</param>
        /// <returns>TRUE if successful, else FALSE.</returns>
        public async Task<bool> DeleteFolderAsync(string folderPath, StorageFolder rootFolder = null)
        {
            if (string.IsNullOrEmpty(folderPath))
            {
                return false;
            }

            rootFolder = rootFolder ?? AntaresBaseFolder.Instance.RoamingFolder;
            StorageFolder deleteFolder;
            try
            {
                deleteFolder = await rootFolder.GetFolderAsync(Path.GetDirectoryName(folderPath));
            }
            catch (Exception ex)
            {
                LogManager.Instance.LogException(ex.ToString());
                return false;
            }

            if (deleteFolder != null)
            {
                await deleteFolder.DeleteAsync();
            }

            return true;
        }
Beispiel #16
0
        public async void accessfolder(StorageFolder folder)
        {
            if (string.Equals(this.folder.Path, folder.Path))
            {
                return;
            }

            writetext = false;

            StorageApplicationPermissions.FutureAccessList.Clear();
            StorageApplicationPermissions.FutureAccessList.Add(folder);

            //image 文件夹
            string str = "image";
            StorageFolder image = null;
            try
            {
                image = await folder.GetFolderAsync(str);
            }
            catch
            {
            }
            if (image == null)
            {
                image = await folder.CreateFolderAsync(str, CreationCollisionOption.OpenIfExists);
            }
            //if (!this.folder.Path.Equals(folder.Path))
            //{
            await storage();
            //}
            this.folder = folder;
        }
        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();
        }
 public FileProvider(StorageFolder resourceLocation, String location, string fileType)
 {
     _fileType = fileType;
     _fileFolder = resourceLocation.GetFolderAsync(location).AsTask().WaitAndUnwrapException();
 }
 public static async Task<StorageFolder> GetFolder(StorageFolder baseFolder, string folderName)
 {
     var found = true;
     StorageFolder folder = null;
     try {
         if (String.IsNullOrEmpty(folderName))
             folder = baseFolder;
         else
             folder = await baseFolder.GetFolderAsync(folderName);
     } catch (FileNotFoundException) {
         found = false;
     }
     if (!found && folderName != null)
         folder = await baseFolder.CreateFolderAsync(folderName, CreationCollisionOption.OpenIfExists);
     return folder;
 }
    /// <summary>
    /// Copy a <see cref="StorageFolder"/> and its content to a specified directory
    /// </summary>
    /// <param name="source">the source folder</param>
    /// <param name="destination">the destination folder where create the copy</param>
    /// <param name="directoryName">the copy directory</param>
    /// <returns></returns>
    public async Task<bool> CopyFolder(StorageFolder source, StorageFolder destination, string directoryName)
    {
      //using (await InstanceLock.LockAsync())
      //{
      var isCopied = true;

      try
      {
        directoryName = directoryName.Replace("/", "\\");
        await CreateDirectory(destination, directoryName);
        var folderDest = await destination.GetFolderAsync(directoryName);
        if (folderDest != null)
        {
          var items = await source.GetItemsAsync();
          foreach (var item in items)
          {
            if (item.IsOfType(StorageItemTypes.File) == true)
            {
              isCopied = await CopyFile(source, folderDest, item.Name);
            }
            else if (item.IsOfType(StorageItemTypes.Folder) == true)
            {
              isCopied = await CopyFolder(source, folderDest, item.Name);
            }

            if (isCopied == false)
            {
              throw new Exception("Fail to copy item");
            }
          }
        }
        else
        {
          throw new Exception("Fail to create new directory");
        }
      }
      catch
      {
        isCopied = false;
      }

      return isCopied;
      //}
    }
        /// <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}");
                }
            });
        }
Beispiel #22
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));
        }
Beispiel #23
0
        /// <summary>
        /// GetFileFromLocalPathUrl
        /// Return the StorageFile associated with the url
        /// </summary>
        /// <param name="PosterUrl">Url string of the content</param>
        /// <returns>StorageFile</returns>
        private async System.Threading.Tasks.Task <Windows.Storage.StorageFile> GetFileFromLocalPathUrl(string PosterUrl)
        {
            string path = null;

            Windows.Storage.StorageFolder folder = null;
            if (PosterUrl.ToLower().StartsWith("picture://"))
            {
                folder = Windows.Storage.KnownFolders.PicturesLibrary;
                path   = PosterUrl.Replace("picture://", "");
            }
            else if (PosterUrl.ToLower().StartsWith("music://"))
            {
                folder = Windows.Storage.KnownFolders.MusicLibrary;
                path   = PosterUrl.Replace("music://", "");
            }
            else if (PosterUrl.ToLower().StartsWith("video://"))
            {
                folder = Windows.Storage.KnownFolders.VideosLibrary;
                path   = PosterUrl.Replace("video://", "");
            }
            else if (PosterUrl.ToLower().StartsWith("file://"))
            {
                path = PosterUrl.Replace("file://", "");
            }
            Windows.Storage.StorageFile file = null;
            try
            {
                if (folder != null)
                {
                    string ext       = System.IO.Path.GetExtension(path);
                    string filename  = System.IO.Path.GetFileName(path);
                    string directory = System.IO.Path.GetDirectoryName(path);
                    while (!string.IsNullOrEmpty(directory))
                    {
                        string subdirectory = directory;
                        int    pos          = -1;
                        if ((pos = directory.IndexOf('\\')) > 0)
                        {
                            subdirectory = directory.Substring(0, pos);
                        }
                        folder = await folder.GetFolderAsync(subdirectory);

                        if (folder != null)
                        {
                            if (pos > 0)
                            {
                                directory = directory.Substring(pos + 1);
                            }
                            else
                            {
                                directory = string.Empty;
                            }
                        }
                    }
                    if (folder != null)
                    {
                        file = await folder.GetFileAsync(filename);
                    }
                }
                else
                {
                    file = await Windows.Storage.StorageFile.GetFileFromPathAsync(path);
                }
            }
            catch (Exception e)
            {
                LogMessage("Exception while opening file: " + PosterUrl + " exception: " + e.Message);
            }
            return(file);
        }
Beispiel #24
0
        public async Task<string> CopyFiles(StorageFolder pFolder)
        {
            var source= await pFolder.GetFolderAsync("{" + SelectedApp.ToString() + "}");
            var destination= await pFolder.GetFolderAsync("{" + SelectedDestinationApp.ToString() + "}");;

            if (source == null || destination == null)
                return "Source or destination not found";

            if ((await destination.GetFilesAsync()).Any() || (await destination.GetFoldersAsync()).Any())
                return "Destination not empty";

            await CopyFiles(source, destination);

            return null;
        }
 /// <summary>
 /// Checks if a folder exists into the <see cref="StorageFolder"/>
 /// </summary>
 /// <param name="storageFolder">the folder where the function has to check</param>
 /// <param name="folderName">the name of the folder</param>
 /// <returns>true if the folder exists, false otherwise</returns>
 public async Task<bool> IsFolderExists(StorageFolder storageFolder, string folderName)
 {
   using (await InstanceLock.LockAsync())
   {
     try
     {
       folderName = folderName.Replace("/", "\\");
       var file = await storageFolder.GetFolderAsync(folderName);
       return (file != null);
     }
     catch
     {
       return false;
     }
   }
 }
    /// <summary>
    /// Removes 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>
    /// <returns>true in case of success. false otherwise</returns>
    public async Task<bool> DeleteFolder(StorageFolder storageFolder, string folderName = null)
    {
      using (await InstanceLock.LockAsync())
      {
        var isDeleted = true;

        try
        {
          var folder = (String.IsNullOrEmpty(folderName) == true) ? storageFolder : await storageFolder.GetFolderAsync(folderName.Replace("/", "\\"));
          if (folder != null)
          {
            await folder.DeleteAsync(StorageDeleteOption.PermanentDelete);
          }
        }
        catch
        {
          isDeleted = false;
        }

        return isDeleted;
      }
    }
Beispiel #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;
            }

        }
        async Task<StorageFile> GetStorageFileFromPathList(StorageFolder sf, List<string> filepath)
        {
            if (sf == null || filepath == null) return null;

            bool getFileCrawler = true;

            while (getFileCrawler || filepath.Count > 1)
            {
                sf = await sf.GetFolderAsync(filepath.FirstOrDefault<string>());

                if (sf != null)
                {
                    filepath.RemoveAt(0);
                }
                else
                {
                    getFileCrawler = false;
                }
            }

            if (sf != null && filepath.Count == 1)
            {
                return await sf.GetFileAsync(filepath.FirstOrDefault<string>());
            }

            return null;
        }
 /// <summary> 
 /// It checks if the specified folder exists. 
 /// </summary> 
 /// <param name="storageFolder">The container folder</param> 
 /// <param name="subFolderName">The sub folder name</param> 
 /// <returns></returns> 
 private static async Task<bool> IfFolderExistsAsync(StorageFolder storageFolder, string subFolderName)
 {
     try
     {
         await storageFolder.GetFolderAsync(subFolderName);
     }
     catch (FileNotFoundException)
     {
         return false;
     }
     catch (Exception)
     {
         throw;
     }
     return true;
 }
 private bool exists(StorageFolder aStore, string aFile) {
     // not supported on win rt phone
     //CommonFileQuery commFile = CommonFileQuery.DefaultQuery;
     //commFile.Equals(aFile);
     //if (aStore.IsCommonFileQuerySupported(commFile)) {
     //    var files = aStore.GetFilesAsync(commFile).AsTask().ConfigureAwait(false).GetAwaiter().GetResult();
     //    if (files.Count > 0)
     //        return true;
     //    else {
     //        CommonFolderQuery commfolder = CommonFolderQuery.DefaultQuery;
     //        commfolder.Equals(aFile);
     //        if (aStore.IsCommonFolderQuerySupported(commfolder)) {
     //            var folders = aStore.GetFoldersAsync(commfolder).AsTask().ConfigureAwait(false).GetAwaiter().GetResult();
     //            if (folders.Count > 0)
     //                return true;
     //            else {
     //                return false;
     //            }
     //        }
     //    }
     //}
     try {
         if (aFile.EndsWith("\\"))
             aFile = aFile.Substring(0, aFile.Length - 1);
         int pos = aFile.LastIndexOf('\\');
         string file = aFile;
         StorageFolder f = aStore;
         if (pos >= 0) {
             string folder = aFile.Substring(0, pos);
             file = aFile.Substring(pos + 1);
             //    if (!exists(aStore, folder)) //recurency to prevent exception
             //   return false;
             f = aStore.GetFolderAsync(folder).AsTask().ConfigureAwait(false).GetAwaiter().GetResult();
         }
         var items = f.GetItemsAsync().AsTask().ConfigureAwait(false).GetAwaiter().GetResult();
         foreach (var item in items) {
             string n = item.Name;
             if (n.Equals(file))
                 return true;
         }
         return false;
     }
     catch (Exception e) {
         return false;
         //bool fileExists;
         //    try {
         //        StorageFile file = aStore.GetFileAsync(aFile).AsTask().ConfigureAwait(false).GetAwaiter().GetResult();
         //        fileExists = file != null;
         //    }
         //    catch (Exception e1) {
         //        fileExists = false;
         //    }
         //    return fileExists;
     }
 }
Beispiel #31
0
        private async Task <FileUploadResponse> HandleUploadAsync(UploadOperation upload, bool start)
        {
            string             response           = string.Empty;
            FileUploadResponse fileUploadResponse = null;

            try
            {
                Progress <UploadOperation> progressCallback = new Progress <UploadOperation>(UploadProgress);

                if (start)
                {
                    // Start the upload and attach a progress handler.
                    await upload.StartAsync().AsTask(cts.Token, progressCallback);
                }
                else
                {
                    // The upload was already running when the application started, re-attach the progress handler.
                    await upload.AttachAsync().AsTask(cts.Token, progressCallback);
                }


                using (var inputStream = upload.GetResultStreamAt(0))
                {
                    using (StreamReader tr = new StreamReader(inputStream.AsStreamForRead()))
                    {
                        response = tr.ReadToEnd();
                    }
                }
                ResponseInformation responseInfo = upload.GetResponseInformation();

                //Handle this response string.
                fileUploadResponse = new FileUploadResponse(response, (int)responseInfo.StatusCode, upload.TransferGroup.Name, responseInfo.Headers);
                if (responseInfo.StatusCode == 200 || responseInfo.StatusCode == 201)
                {
                    FileUploadCompleted(this, fileUploadResponse);
                }
                else
                {
                    FileUploadError(this, fileUploadResponse);
                }
            }
            catch (TaskCanceledException)
            {
                fileUploadResponse = new FileUploadResponse("Upload canceled", -1, upload.TransferGroup.Name, null);
                FileUploadError(this, fileUploadResponse);
            }
            catch (Exception ex)
            {
                if (!IsExceptionHandled("Error", ex, upload))
                {
                    fileUploadResponse = new FileUploadResponse(ex.ToString() + $" * {response}", -1, upload.TransferGroup.Name, null);
                    FileUploadError(this, fileUploadResponse);
                }
            }finally
            {
                //Clear all temporal files
                try
                {
                    Windows.Storage.StorageFolder storageFolder = Windows.Storage.ApplicationData.Current.LocalFolder;
                    var tmpFolder = await storageFolder.GetFolderAsync($"tmp-{upload.TransferGroup.Name}");

                    if (tmpFolder != null)
                    {
                        await tmpFolder.DeleteAsync();
                    }
                }
                catch (System.IO.FileNotFoundException ex)
                {
                }
            }

            return(fileUploadResponse);
        }
Beispiel #32
0
		public static async Task DeleteFoldersRecursively(StorageFolder folder, string folderName)
		{
			folder = await folder.GetFolderAsync(folderName);
			await folder.DeleteAsync();
		}
Beispiel #33
-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
            }
            
        }