示例#1
0
        /// <summary>
        /// Estimate the number of elements in this storage as the size of the storage divided by the size of the elements
        /// </summary>
        /// <returns>An estimation of the number of elements in this storage</returns>
        public async System.Threading.Tasks.Task <int> EstimateSize()
        {
            StorageFile file;

            try
            {
                file = await StorageFile.GetFileFromPathAsync(_fileInfo);
            }
            catch
            {
                //file doesn't exist
                return(0);
            }
            Windows.Storage.FileProperties.BasicProperties properties = await file.GetBasicPropertiesAsync();

            return((int)(properties.Size / ((ulong)_elementSize)));
        }
示例#2
0
        async private void SearchFiles(StorageFolder folder)
        {
            IReadOnlyList <StorageFile> fileList = await folder.GetFilesAsync();

            foreach (StorageFile file in fileList)
            {
                if (file.DisplayName.IndexOf(searchPattern.Text) >= 0)
                {
                    Windows.Storage.FileProperties.BasicProperties basicProperties = await file.GetBasicPropertiesAsync();

                    string fileSize = ParseSize(basicProperties.Size);

                    filelist.Add(new Item {
                        Filename = file.DisplayName, Size = fileSize, File = file
                    });
                }
            }
        }
示例#3
0
文件: Item.cs 项目: Deltaecho1/textie
        public async void ShowFileInfoDialog()
        {
            Windows.Storage.FileProperties.BasicProperties basicProperties =
                await File.GetBasicPropertiesAsync();

            ContentDialog FileInfoDialog = new ContentDialog()
            {
                PrimaryButtonText = "OK"
            };

            FileInfoDialog.Title = "File Information";

            StackPanel ContentStackPanel = new StackPanel();

            ContentStackPanel.Children.Add(new TextBlock()
            {
                Text = FileName, FontSize = 17
            });
            ContentStackPanel.Children.Add(new TextBlock()
            {
                Text = FilePath, FontSize = 12
            });
            ContentStackPanel.Children.Add(new TextBlock()
            {
                Text = "File type: " + FileType
            });
            ContentStackPanel.Children.Add(new TextBlock()
            {
                Text = "File size: " + basicProperties.Size + " bytes"
            });
            ContentStackPanel.Children.Add(new TextBlock()
            {
                Text = "Date created: " + File.DateCreated.DateTime
            });
            ContentStackPanel.Children.Add(new TextBlock()
            {
                Text = "Date modified: " + basicProperties.DateModified.DateTime
            });

            FileInfoDialog.Content = ContentStackPanel;

            await FileInfoDialog.ShowAsync();
        }
        private async void SetMediaFile(Windows.Storage.StorageFile mediaFile)
        {
            const string fileDurationProperty = "System.Media.Duration";

            if (mediaFile.ContentType.Contains("video"))
            {
                sIsVideoFile = true;
            }
            else if (mediaFile.ContentType.Contains("audio"))
            {
                sIsVideoFile = false;
            }
            else
            {
                return;
            }

            var stream = await mediaFile.OpenAsync(Windows.Storage.FileAccessMode.Read);

            mediaElement.SetSource(stream, mediaFile.ContentType);

            // Get file's basic properties.
            var propertyNames = new List <string>();

            propertyNames.Add(fileDurationProperty);
            Windows.Storage.FileProperties.BasicProperties basicProperties =
                await mediaFile.GetBasicPropertiesAsync();

            IDictionary <string, object> extraProperties = await mediaFile.Properties.RetrievePropertiesAsync(propertyNames);

            UInt64 durationTime = (UInt64)extraProperties[fileDurationProperty];

            durationTime        = durationTime / 10000;/*msに変換*/
            TB_MaxTime.Text     = GetTimeSpanStr(durationTime);
            BT_Resume.IsEnabled = true;
            BT_Stop.IsEnabled   = true;
            SL_Time.IsEnabled   = true;
            SL_Time.Maximum     = durationTime;

            TB_MediaPath.Text = mediaFile.Path.ToString();
        }
        /// <summary>
        /// Populates the page with content passed during navigation.  Any saved state is also
        /// provided when recreating a page from a prior session.
        /// </summary>
        /// <param name="navigationParameter">The parameter value passed to
        /// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested.
        /// </param>
        /// <param name="pageState">A dictionary of state preserved by this page during an earlier
        /// session.  This will be null the first time a page is visited.</param>
        protected async override void LoadState(Object navigationParameter, Dictionary <String, Object> pageState)
        {
            // Allow saved page state to override the initial item to display
            if (pageState != null && pageState.ContainsKey("SelectedItem"))
            {
                navigationParameter = pageState["SelectedItem"];
            }

            var currentItem = SampleDataSource.GetItem((String)navigationParameter);

            this.DefaultViewModel["Group"] = currentItem.Group;
            this.DefaultViewModel["Items"] = currentItem.Group.Items;

            this.pageTitle.Text        = "Hindu Calendar - " + currentItem.Title + " " + currentItem.Year.ToString();
            this.cityTitle.Text        = currentItem.Group.city._Name;
            this.flipView.SelectedItem = currentItem;

            StorageFile privateEventFile = await ApplicationData.Current.RoamingFolder.CreateFileAsync("PrivateEvents.txt", CreationCollisionOption.OpenIfExists);

            Windows.Storage.FileProperties.BasicProperties prop = await privateEventFile.GetBasicPropertiesAsync();

            if (prop.Size != 0)
            {
                Stream stream = await privateEventFile.OpenStreamForReadAsync();

                DataContractSerializer ser = new DataContractSerializer(typeof(PrivateEvents));
                _privateEvents = (PrivateEvents)ser.ReadObject(stream);
                // If we have a zero size file or no events, we can get this too
                stream.Dispose();
            }

            if (_privateEvents == null)
            {
                _privateEvents = new PrivateEvents();
            }
            await SampleDataSource.GetClosestCity();

            CancelTimerTrigger();
            UpdateTitle();
            ScheduleTiles(currentItem);
        }
示例#6
0
        // The real disk space work is done here within some asynchronous stuff
        private async static Task <string> infoTask()
        {
            Result result = new Result();

            // Run folder discovery into another Thread to not block UI Thread
            await Task.Run(async() =>
            {
                foreach (var folder in APP_FOLDERS)
                {
                    var query        = folder.CreateFileQuery();
                    var files        = await query.GetFilesAsync();
                    ulong folderSize = 0;
                    foreach (Windows.Storage.StorageFile file in files)
                    {
                        // Get file's basic properties.
                        Windows.Storage.FileProperties.BasicProperties basicProperties =
                            await file.GetBasicPropertiesAsync();

                        folderSize += (ulong)basicProperties.Size;
                    }

                    result.app += folderSize;
                }
            });

            await getExtraProperties().ContinueWith(propertiesTask =>
            {
                result.free  = (ulong)propertiesTask.Result["System.FreeSpace"];
                result.total = (ulong)propertiesTask.Result["System.Capacity"];
            });

            // Return JSON Result

            JsonObject jsonObject = new JsonObject();

            jsonObject.SetNamedValue("app", JsonValue.CreateNumberValue(result.app));
            jsonObject.SetNamedValue("free", JsonValue.CreateNumberValue(result.free));
            jsonObject.SetNamedValue("total", JsonValue.CreateNumberValue(result.total));

            return(jsonObject.ToString());
        }
        public static async Task <List <MasterDictionary> > Load(string FileName)
        {
            List <MasterDictionary> DataList = new List <MasterDictionary>();

            Windows.Storage.StorageFolder storageFolder = Windows.Storage.ApplicationData.Current.LocalFolder;

            var file = await storageFolder.TryGetItemAsync(FileName);

            if (file != null)
            {
                Windows.Storage.FileProperties.BasicProperties basicProperties = await file.GetBasicPropertiesAsync();

                if (basicProperties.Size > 0)
                {
                    using (var Stream = await storageFolder.OpenStreamForReadAsync(FileName))
                    {
                        //starts to hang here
                        System.Xml.XmlDictionaryReader XmlReader = System.Xml.XmlDictionaryReader.CreateTextReader(Stream, new System.Xml.XmlDictionaryReaderQuotas());
                        //doesn't get further than here??
                        System.Runtime.Serialization.DataContractSerializer Serializer = new System.Runtime.Serialization.DataContractSerializer(typeof(List <MasterDictionary>));
                        var data = (MasterDictionary)Serializer.ReadObject(XmlReader);
                        DataList.Add(data);
                    }


                    return(DataList);
                }
                else
                {
                    return(new List <MasterDictionary>());
                }

                //return new List<MasterDictionary>();
            }
            else
            {
                //Console.WriteLine("No File Found");
                return(new List <MasterDictionary>());
            }
        }
示例#8
0
        ///// <summary>
        ///// Формирует список файлов содержащихся в указанном каталоге
        ///// Файлы включаются в результирующий список если удовлетворяют условиям определённым в параметре options
        ///// </summary>
        ///// <param name="folder">
        ///// каталог в котором искать файлы
        ///// </param>
        ///// <param name="filelist">
        ///// Список найденных файлов
        ///// </param>
        ///// <param name="options">
        ///// условия которым должен удовлетворять файл для включения в список файлов
        ///// </param>
        ///// <returns></returns>

        /// <summary>
        /// Формирует список файлов содержащихся в указанном каталоге
        /// Файлы включаются в результирующий список если удовлетворяют условиям определённым в параметре options
        /// </summary>
        /// <param name="folder">
        /// каталог в котором искать файлы
        /// </param>
        /// <param name="filelist">
        /// Список найденных файлов
        /// </param>
        /// <param name="options">
        /// условия которым должен удовлетворять файл для включения в список файлов
        /// </param>
        /// <returns></returns>
        private async Task GetFolderFiles(Folder folder, CancellationToken canselationToken, OperationStatus status)
        {
            status.Id = SearchStatus.NewFileSelected;
            var progress = _progress as IProgress <OperationStatus>;

            try // Каталог может быть удалён после того как начался поиск дубликатов
            {
                var storageFolder = await StorageFolder.GetFolderFromPathAsync(folder.FullName);

                List <string> l = new List <string>();
                l.AddRange(_fileSelectionOptions.FileTypeFilter.Where(f => f != ""));
                var queryOptions = new QueryOptions(CommonFileQuery.OrderByName, _fileSelectionOptions.FileTypeFilter.Where(f => f != ""));
                var query        = storageFolder.CreateFileQueryWithOptions(queryOptions);
                foreach (StorageFile item in await query.GetFilesAsync())
                {
                    canselationToken.ThrowIfCancellationRequested();

                    if (_fileSelectionOptions.ExcludeExtentions.Contains(item.FileType))
                    {
                        continue;
                    }

                    File file = new File(item.Name, item.Path, item.FileType, item.DateCreated.DateTime,
                                         new DateTime(), 0, folder.IsPrimary, folder.IsProtected);
                    Windows.Storage.FileProperties.BasicProperties basicproperties = await item.GetBasicPropertiesAsync();

                    file.DateModifyed = basicproperties.DateModified.DateTime;
                    file.Size         = basicproperties.Size;
                    _filesCollection.Add(file);
                    ++status.HandledItems;
                    progress.Report(status);
                }
            }
            catch (FileNotFoundException ex)
            {
                status.Id      = SearchStatus.Error;
                status.Message = $"{ex.Message} ' {folder.FullName} '";
                throw new OperationCanceledException();
            }
        }
示例#9
0
        public async Task CreateFile()
        {
            await DispatcherHelper.ExecuteOnUIThreadAsync(async() =>
            {
                var folderPicker = new FolderPicker();
                StorageFolder folder;
                folderPicker.SuggestedStartLocation = PickerLocationId.Desktop;

                foreach (string ext in FileTypes.List_Type_extensions)
                {
                    folderPicker.FileTypeFilter.Add(ext);
                }

                folder = await folderPicker.PickSingleFolderAsync();
                if (folder != null)
                {
                    StorageFile file = await folder.CreateFileAsync(Tab.TabName, CreationCollisionOption.OpenIfExists);
                    Windows.Storage.AccessCache.StorageApplicationPermissions.FutureAccessList.Add(file);
                    Windows.Storage.FileProperties.BasicProperties date = await file.GetBasicPropertiesAsync(); Tab.TabDateModified = date.DateModified.ToString();

                    foreach (string type in FileTypes.List_Type_extensions)
                    {
                        if (Tab.TabName.Contains(type))
                        {
                            Tab.TabType = FileTypes.GetExtensionType(file.FileType);
                            break;
                        }
                        else
                        {
                            continue;
                        }
                    }
                    Tab.PathContent = file.Path;
                    await TabsWriteManager.PushUpdateTabAsync(Tab, ListTabsID);
                }
            });
        }
示例#10
0
        private async void Settings_Loaded(object sender, RoutedEventArgs e)
        {
            // Themes

            if (_appSettings.Values.ContainsKey("Themes"))
            {
                theme_s.SelectedIndex = Convert.ToInt32(_appSettings.Values["Themes"]);
            }
            else
            {
                theme_s.SelectedIndex = 0;
            }

            //Offline Mode
            if (_appSettings.Values.ContainsKey("OfflineMode"))
            {
                offline_m.IsOn = Convert.ToBoolean(_appSettings.Values["OfflineMode"]);
            }
            else
            {
                offline_m.IsOn = false;
                _appSettings.Values["OfflineMode"] = offline_m.IsOn;
            }

            //URI History
            if (await Base.IsFilePresent("history.log"))
            {
                Windows.Storage.FileProperties.BasicProperties basicProperties = await(await ApplicationData.Current.LocalFolder.GetFileAsync("history.log")).GetBasicPropertiesAsync();
                string fileSize = string.Format("{0:##0.###}", basicProperties.Size * 0.001);
                history_content.Text = fileSize + " KB";
            }
            else
            {
                history_content.Text = "0 KB";
            }
        }
示例#11
0
        public async void Open()
        {
            var picker = new FileOpenPicker
            {
                ViewMode = PickerViewMode.List,
                SuggestedStartLocation = PickerLocationId.DocumentsLibrary,
            };

            picker.FileTypeFilter.Add(".txt");

            var file = await picker.PickSingleFileAsync();

            if (file == null)
            {
                await new Windows.UI.Popups.MessageDialog("No file selected !").ShowAsync();
            }
            else
            {
                File = await _fileService.LoadAsync(file);
            }


            List <string> fileProperties = new List <string>();

            fileProperties.Add("File name: " + file.Name);
            fileProperties.Add("File type: " + file.FileType);

            // Get file's basic properties.
            Windows.Storage.FileProperties.BasicProperties basicProperties =
                await file.GetBasicPropertiesAsync();

            string fileSize = string.Format("{0:n0}", basicProperties.Size);

            fileProperties.Add("File size: " + fileSize + " bytes");
            fileProperties.Add("Date modified: " + basicProperties.DateModified);

            // Define property names to be retrieved for Extended properties.
            const string dateAccessedProperty = "System.DateAccessed";
            const string fileOwnerProperty    = "System.FileOwner";

            var propertyNames = new List <string>();

            propertyNames.Add(dateAccessedProperty);
            propertyNames.Add(fileOwnerProperty);

            // Get extended properties.
            IDictionary <string, object> extraProperties =
                await file.Properties.RetrievePropertiesAsync(propertyNames);

            // Get date-accessed property.
            var propValue = extraProperties[dateAccessedProperty];

            if (propValue != null)
            {
                fileProperties.Add("Date accessed: " + propValue);
            }

            // Get file-owner property.
            propValue = extraProperties[fileOwnerProperty];
            if (propValue != null)
            {
                fileProperties.Add("File owner: " + propValue);
            }

            FileProperties = fileProperties;
        }
示例#12
0
 internal BasicProperties(Windows.Storage.FileProperties.BasicProperties properties)
 {
     _properties = properties;
 }
示例#13
0
        /// <summary>
        /// Will save a field work copy, from local state folder to user selected output folder from a save picker dialog
        /// </summary>
        public async Task <string> SaveDBCopy(string currentDBPath = "", string currentUserCode = "")
        {
            //Variables
            string outputSaveFilePath = string.Empty;

            //Create a file save picker for sqlite
            var fileSavePicker = new Windows.Storage.Pickers.FileSavePicker();

            fileSavePicker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.Desktop;
            fileSavePicker.FileTypeChoices.Add("sqlite", new List <string>()
            {
                ".sqlite"
            });
            fileSavePicker.DefaultFileExtension = ".sqlite";
            fileSavePicker.SuggestedFileName    = CalculateDBCopyName(currentUserCode); //Should be something like Geolcode_YYYYMMDD_GSCFieldwork.sqlite

            //Get users selected save files
            StorageFile savefile = await fileSavePicker.PickSaveFileAsync(); //This will save an empty file at the location user has selected

            //Get user local state database as binary buffer
            if (currentDBPath == string.Empty)
            {
                currentDBPath = DataAccess.DbPath;
            }
            StorageFile fileToRead = await StorageFile.GetFileFromPathAsync(currentDBPath);

            if (fileToRead != null)
            {
                IBuffer currentDBBuffer = await Windows.Storage.FileIO.ReadBufferAsync(fileToRead as IStorageFile);

                byte[] currentDBByteArray = currentDBBuffer.ToArray();

                if (savefile != null)
                {
                    //Lock the file
                    Windows.Storage.CachedFileManager.DeferUpdates(savefile);

                    //Save
                    await Windows.Storage.FileIO.WriteBytesAsync(savefile, currentDBByteArray);

                    Windows.Storage.Provider.FileUpdateStatus status = await Windows.Storage.CachedFileManager.CompleteUpdatesAsync(savefile);

                    if (status == Windows.Storage.Provider.FileUpdateStatus.Complete)
                    {
                        //Show end message
                        var           loadLocalization = Windows.ApplicationModel.Resources.ResourceLoader.GetForCurrentView();
                        ContentDialog endProcessDialog = new ContentDialog()
                        {
                            Title             = loadLocalization.GetString("SaveDBDialogTitle"),
                            Content           = loadLocalization.GetString("SaveDBDialogContent") + "\n" + savefile.Path.ToString(),
                            PrimaryButtonText = loadLocalization.GetString("LoadDataButtonProcessEndMessageOk")
                        };

                        ContentDialogResult cdr = await endProcessDialog.ShowAsync();
                    }
                    else
                    {
                        //Show error message
                        var           loadLocalization = Windows.ApplicationModel.Resources.ResourceLoader.GetForCurrentView();
                        ContentDialog endProcessDialog = new ContentDialog()
                        {
                            Title             = loadLocalization.GetString("SaveDBDialogTitle"),
                            Content           = loadLocalization.GetString("SaveDBDialogContentError"),
                            PrimaryButtonText = loadLocalization.GetString("LoadDataButtonProcessEndMessageOk")
                        };

                        ContentDialogResult cdr = await endProcessDialog.ShowAsync();
                    }

                    //Last validation just in case
                    Windows.Storage.FileProperties.BasicProperties baseProp = await savefile.GetBasicPropertiesAsync();

                    if (baseProp.Size == 0)
                    {
                        //Show error message
                        var           loadLocalization = Windows.ApplicationModel.Resources.ResourceLoader.GetForCurrentView();
                        ContentDialog endProcessDialog = new ContentDialog()
                        {
                            Title             = loadLocalization.GetString("SaveDBDialogTitle"),
                            Content           = loadLocalization.GetString("SaveDBDialogContentError"),
                            PrimaryButtonText = loadLocalization.GetString("LoadDataButtonProcessEndMessageOk")
                        };

                        endProcessDialog.Style = (Style)Application.Current.Resources["DeleteDialog"];
                        ContentDialogResult cdr = await endProcessDialog.ShowAsync();
                    }
                }
            }

            if (savefile != null && savefile.Path != null)
            {
                outputSaveFilePath = savefile.Path;
            }

            return(outputSaveFilePath);
        }
示例#14
0
 private BasicProperties(Windows.Storage.FileProperties.BasicProperties properties)
 {
     _properties = properties;
 }
示例#15
0
        async private void PrintCwd()
        {
            filelist.Clear();
            // add ..
            StorageFolder parent = await CurrentFolder.GetParentAsync();

            if (parent != null)
            {
                searchPattern.Text = "";
                filelist.Add(new Item {
                    Filename = "..", Size = "FOLDER", Folder = parent
                });
            }
            else
            {
                searchPattern.Text = ("Lack of permissions :(");
                if (previousLocation != null)
                {
                    filelist.Add(new Item {
                        Filename = "BACK", Size = "FOLDER", Folder = previousLocation
                    });
                }
            }

            IReadOnlyList <StorageFolder> folderList = await CurrentFolder.GetFoldersAsync();

            foreach (StorageFolder folder in folderList)
            {
                filelist.Add(new Item {
                    Filename = folder.DisplayName, Size = "FOLDER", Folder = folder
                });
            }

            IReadOnlyList <StorageFile> fileList = await CurrentFolder.GetFilesAsync();

            foreach (StorageFile file in fileList)
            {
                Windows.Storage.FileProperties.BasicProperties basicProperties = await file.GetBasicPropertiesAsync();

                string fileSize = ParseSize(basicProperties.Size);

                filelist.Add(new Item {
                    Filename = file.DisplayName, Size = fileSize, File = file
                });
            }

            // move ..
            for (int i = 0; i < filelist.Count; ++i)
            {
                if (filelist[i].Filename == ".." || filelist[i].Filename == "BACK")
                {
                    Item item = filelist[i];
                    filelist.RemoveAt(i);
                    filelist.Insert(0, item);
                }
            }



            return;
        }
示例#16
0
        private async void AppBarButton_Click(object sender, RoutedEventArgs e)
        {
            Ring.IsActive = true;
            try
            {
                var picker = new Windows.Storage.Pickers.FileOpenPicker();
                picker.ViewMode = Windows.Storage.Pickers.PickerViewMode.Thumbnail;
                picker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.PicturesLibrary;
                // picker.FileTypeFilter.Add(".bin");
                // picker.FileTypeFilter.Add(".txt");
                picker.FileTypeFilter.Add("*");
                Windows.Storage.StorageFile file = await picker.PickSingleFileAsync();

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



                    byte[] bb = buffer.ToArray();
                    Windows.Storage.FileProperties.BasicProperties basicProperties = await file.GetBasicPropertiesAsync();

                    // ViewModel.newVid();



                    int icol = 0;
                    if (ViewModel.ColTabs.Count > 0)
                    {
                        if (ViewModel.ColTabs[0].Name == "New File")
                        {
                            try
                            {
                                VidDoc vidDoc = new VidDoc()
                                {
                                    Name    = file.DisplayName,
                                    Sppan   = true,
                                    ccc     = cout,
                                    IsShow  = Visibility.Visible,
                                    IsShow1 = Visibility.Visible,

                                    Poz      = 0,
                                    Path     = file.Path,
                                    Size     = basicProperties.Size.ToString(),
                                    NameType = file.FileType
                                               //  BiteFile=bb
                                };

                                ViewModel.ColTabs.Add(vidDoc);

                                //   cout++;
                                ViewModel.ColTabs.RemoveAt(0);
                                Tabs.SelectedIndex = 0;
                                vidDoc.bb1         = bb;
                                await vidDoc.OpenF();

                                //Tabs.SelectedIndex = 0;
                                cout++;
                            }
                            catch (Exception ex)
                            {
                                MessageDialog messageDialog = new MessageDialog(ex.ToString());
                                await messageDialog.ShowAsync();
                            }
                        }
                        else
                        {
                            icol = Tabs.SelectedIndex;
                            ViewModel.ColTabs.RemoveAt(icol);
                            VidDoc vidDoc = new VidDoc()
                            {
                                //uuu
                                //jjj
                                Name    = file.DisplayName,
                                Sppan   = true,
                                ccc     = cout,
                                IsShow  = Visibility.Visible,
                                IsShow1 = Visibility.Visible,

                                Poz      = 0,
                                Path     = file.Path,
                                Size     = basicProperties.Size.ToString(),
                                NameType = file.FileType
                                           //   bb1 = bb
                                           //  BiteFile=bb
                            };
                            ViewModel.ColTabs.Insert(icol, vidDoc);
                            Tabs.SelectedIndex = icol;
                            vidDoc.bb1         = bb;
                            await vidDoc.OpenF();

                            cout++;
                        }
                    }
                    else
                    {
                        VidDoc vidDoc = new VidDoc()
                        {
                            //uuu
                            //jjj
                            Name    = file.DisplayName,
                            Sppan   = true,
                            ccc     = cout,
                            IsShow  = Visibility.Visible,
                            IsShow1 = Visibility.Visible,

                            Poz      = 0,
                            Path     = file.Path,
                            Size     = basicProperties.Size.ToString(),
                            NameType = file.FileType
                                       //   bb1 = bb
                                       //  BiteFile=bb
                        };
                        ViewModel.ColTabs.Add(vidDoc);
                        cout++;
                        Tabs.SelectedIndex = ViewModel.ColTabs.Count - 1;
                        vidDoc.bb1         = bb;
                        await vidDoc.OpenF();
                    }
                    Ring.IsActive = false;
                }
                else
                {
                    Ring.IsActive = false;
                    MessageDialog f = new MessageDialog("Файл не открыт");
                    await f.ShowAsync();
                }
            }
            catch
            {
                Ring.IsActive = false;
                MessageDialog f = new MessageDialog("Произошла ошибка, возможно файл поврежден");
                await f.ShowAsync();
            }
            Ring.IsActive = false;
        }
示例#17
0
        private async void OpenNewFile(object sender, RoutedEventArgs e)
        {
            // ViewModel.IsShowBar = Visibility.Visible;
            Ring.IsActive = true;
            try
            {
                var picker = new Windows.Storage.Pickers.FileOpenPicker();
                picker.ViewMode = Windows.Storage.Pickers.PickerViewMode.Thumbnail;
                picker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.PicturesLibrary;
                //  picker.FileTypeFilter.Add(".bin");
                //  picker.FileTypeFilter.Add(".txt");
                // picker.FileTypeFilter.Add(".doc");
                picker.FileTypeFilter.Add("*");
                Windows.Storage.StorageFile file = await picker.PickSingleFileAsync();

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

                    byte[] bb = buffer.ToArray();
                    Windows.Storage.FileProperties.BasicProperties basicProperties = await file.GetBasicPropertiesAsync();

                    VidDoc vidDoc = new VidDoc()
                    {
                        //uuu
                        //jjj
                        Name     = file.DisplayName,
                        Sppan    = true,
                        ccc      = cout,
                        IsShow   = Visibility.Visible,
                        IsShow1  = Visibility.Visible,
                        Poz      = 0,
                        Path     = file.Path,
                        Size     = basicProperties.Size.ToString(),
                        NameType = file.FileType
                                   //   bb1 = bb
                                   //  BiteFile=bb
                    };
                    await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                    {
                        ViewModel.ColTabs.Add(vidDoc
                                              );
                    });

                    if (ViewModel.ColTabs[0].Name == "New File")
                    {
                        ViewModel.ColTabs.RemoveAt(0);
                    }


                    cout++;
                    await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                    {
                        Tabs.SelectedIndex = ViewModel.ColTabs.Count - 1;
                    });

                    await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                    {
                        vidDoc.bb1 = bb;
                    });

                    await vidDoc.OpenF();
                    await OpenF(bb, vidDoc);

                    //ViewModel.IsShowBar = Visibility.Collapsed;
                    Ring.IsActive = false;
                }
                else
                {
                    MessageDialog f = new MessageDialog("Файл не открыт");
                    await f.ShowAsync();

                    Ring.IsActive = false;
                }
            }
            catch
            {
                MessageDialog f = new MessageDialog("Произошла ошибка, возможно файл поврежден");
                await f.ShowAsync();

                Ring.IsActive = false;
            }
            Ring.IsActive = false;
        }
示例#18
0
        private async Task SendFileAsync(String url, StorageFile sFile, HttpMethod httpMethod)
        {
            //Log data for upload attempt
            Windows.Storage.FileProperties.BasicProperties fileProperties = await sFile.GetBasicPropertiesAsync();

            Dictionary <string, string> properties = new Dictionary <string, string> {
                { "File Size", fileProperties.Size.ToString() }
            };

            App.Controller.TelemetryClient.TrackEvent("OneDrive picture upload attempt", properties);
            HttpStreamContent streamContent = null;

            try
            {
                //Open file to send as stream
                Stream stream = await sFile.OpenStreamForReadAsync();

                streamContent = new HttpStreamContent(stream.AsInputStream());
                Debug.WriteLine("SendFileAsync() - sending: " + sFile.Path);
            }
            catch (FileNotFoundException ex)
            {
                Debug.WriteLine(ex.Message);

                // Log telemetry event about this exception
                var events = new Dictionary <string, string> {
                    { "OneDrive", ex.Message }
                };
                App.Controller.TelemetryClient.TrackEvent("FailedToOpenFile", events);
            }
            catch (Exception ex)
            {
                // Log telemetry event about this exception
                var events = new Dictionary <string, string> {
                    { "OneDrive", ex.Message }
                };
                App.Controller.TelemetryClient.TrackEvent("FailedToOpenFile", events);

                throw new Exception("SendFileAsync() - Cannot open file. Err= " + ex.Message);
            }

            if (streamContent == null)
            {
                //Throw exception if stream is not created
                Debug.WriteLine("  File Path = " + (sFile != null ? sFile.Path : "?"));
                throw new Exception("SendFileAsync() - Cannot open file.");
            }

            try
            {
                Uri resourceAddress = new Uri(url);
                //Create requst to upload file
                using (HttpRequestMessage request = new HttpRequestMessage(httpMethod, resourceAddress))
                {
                    request.Content = streamContent;

                    // Do an asynchronous POST.
                    using (HttpResponseMessage response = await httpClient.SendRequestAsync(request).AsTask(cts.Token))
                    {
                        await DebugTextResultAsync(response);

                        if (response.StatusCode != HttpStatusCode.Created)
                        {
                            throw new Exception("SendFileAsync() - " + response.StatusCode);
                        }
                    }
                }
            }
            catch (TaskCanceledException ex)
            {
                // Log telemetry event about this exception
                var events = new Dictionary <string, string> {
                    { "OneDrive", ex.Message }
                };
                App.Controller.TelemetryClient.TrackEvent("CancelledFileUpload", events);

                throw new Exception("SendFileAsync() - " + ex.Message);
            }
            catch (Exception ex)
            {
                // This failure will already be logged in telemetry in the enclosing UploadPictures function. We don't want this to be recorded twice.

                throw new Exception("SendFileAsync() - Error: " + ex.Message);
            }
            finally
            {
                streamContent.Dispose();
                Debug.WriteLine("SendFileAsync() - final.");
            }

            App.Controller.TelemetryClient.TrackEvent("OneDrive picture upload success", properties);
        }
示例#19
0
        public async void ShowFileInfoDialog()
        {
            Windows.Storage.FileProperties.BasicProperties basicProperties =
                await File.GetBasicPropertiesAsync();

            ContentDialog FileInfoDialog = new ContentDialog()
            {
                PrimaryButtonText = "OK"
            };

            FileInfoDialog.Title = "File Information";

            StackPanel ContentStackPanel = new StackPanel();

            ContentStackPanel.Children.Add(new TextBlock()
            {
                Text = FileName, FontSize = 17
            });

            RelativePanel FileStackPanel = new RelativePanel();

            TextBlock filePathTextBlock = new TextBlock()
            {
                Text = FilePath, FontSize = 12, IsTextSelectionEnabled = true, TextWrapping = TextWrapping.NoWrap, Padding = new Thickness(4)
            };
            ScrollViewer filePathScrollViewer = new ScrollViewer()
            {
                Content = filePathTextBlock, HorizontalScrollBarVisibility = ScrollBarVisibility.Auto, MaxWidth = 320, Margin = new Thickness(0, 0, 90, 0)
            };
            Button openFolderButton = new Button()
            {
                Content = "Open folder", FontSize = 12
            };

            FileStackPanel.Children.Add(filePathScrollViewer);
            FileStackPanel.Children.Add(openFolderButton);

            ContentStackPanel.Children.Add(FileStackPanel);

            openFolderButton.Click += OpenFolderButton_Click;

            ContentStackPanel.Children.Add(new TextBlock()
            {
                Text = "File type: " + FileType
            });
            ContentStackPanel.Children.Add(new TextBlock()
            {
                Text = "File size: " + basicProperties.Size + " bytes"
            });
            ContentStackPanel.Children.Add(new TextBlock()
            {
                Text = "Date created: " + File.DateCreated.DateTime
            });
            ContentStackPanel.Children.Add(new TextBlock()
            {
                Text = "Date modified: " + basicProperties.DateModified.DateTime
            });

            FileInfoDialog.Content = ContentStackPanel;

            RelativePanel.SetAlignLeftWithPanel(filePathScrollViewer, true);
            RelativePanel.SetAlignRightWithPanel(openFolderButton, true);

            await FileInfoDialog.ShowAsync();
        }