示例#1
0
        // Write Stream(通过 StorageStreamTransaction 写)
        private async void btnWriteStream2_Click(object sender, RoutedEventArgs e)
        {
            // 在指定的目录下创建指定的文件
            StorageFolder storageFolder = await KnownFolders.GetFolderForUserAsync(null, KnownFolderId.DocumentsLibrary);

            StorageFile storageFile = await storageFolder.CreateFileAsync("webabcdStream.txt", CreationCollisionOption.ReplaceExisting);

            string textContent = "I am webabcd(StorageStreamTransaction)";

            using (StorageStreamTransaction transaction = await storageFile.OpenTransactedWriteAsync())
            {
                using (DataWriter dataWriter = new DataWriter(transaction.Stream))
                {
                    // 将字符串写入数据流
                    dataWriter.WriteString(textContent);

                    // 使用 StorageStreamTransaction 方式的话,调用 DataWriter 的 StoreAsync() 方法的作用是把数据写入临时文件
                    // 以本例为例,这个临时文件就是同目录下名为 webabcdStream.txt.~tmp 的文件。只要不调用 CommitAsync() 方法的话就会看到
                    // 返回值为写入数据的大小,需要通过此值更新 StorageStreamTransaction 中的 Stream 的大小
                    transaction.Stream.Size = await dataWriter.StoreAsync();

                    // 重命名临时文件
                    await transaction.CommitAsync();

                    lblMsg.Text = "写入成功";
                }
            }
        }
示例#2
0
        // Write Stream(通过 IRandomAccessStream 写)
        private async void btnWriteStream1_Click(object sender, RoutedEventArgs e)
        {
            // 在指定的目录下创建指定的文件
            StorageFolder storageFolder = await KnownFolders.GetFolderForUserAsync(null, KnownFolderId.DocumentsLibrary);

            StorageFile storageFile = await storageFolder.CreateFileAsync("webabcdStream.txt", CreationCollisionOption.ReplaceExisting);

            string textContent = "I am webabcd(IRandomAccessStream)";

            if (storageFile != null)
            {
                using (IRandomAccessStream randomStream = await storageFile.OpenAsync(FileAccessMode.ReadWrite))
                {
                    using (DataWriter dataWriter = new DataWriter(randomStream))
                    {
                        // 将字符串写入数据流
                        dataWriter.WriteString(textContent);

                        // 将数据流写入文件
                        await dataWriter.StoreAsync();

                        lblMsg.Text = "写入成功";
                    }
                }
            }
        }
示例#3
0
        private async void btnCopyFile_Click(object sender, RoutedEventArgs e)
        {
            // 用户选中的可移动存储
            string folderName = (string)listBox.SelectedItem;

            if (folderName != null)
            {
                StorageFolder removableDevices = await KnownFolders.GetFolderForUserAsync(null, KnownFolderId.RemovableDevices);

                StorageFolder storageFolder = await removableDevices.GetFolderAsync(folderName);

                // 复制包内文件到指定的可移动存储
                StorageFile storageFile = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///Assets/hololens.jpg"));

                try
                {
                    await storageFile.CopyAsync(storageFolder, "hololens.jpg", NameCollisionOption.ReplaceExisting);

                    lblMsg.Text = "复制成功";
                }
                catch (Exception ex)
                {
                    lblMsg.Text = ex.ToString();
                }
            }
        }
示例#4
0
        private async void Button_Click(object sender, RoutedEventArgs e)
        {
            StorageFolder storageFolder = await KnownFolders.GetFolderForUserAsync(null, KnownFolderId.VideosLibrary);

            //CopyAsync接收三个参数,保存文件夹,新的文件名,保存方式(重名是否替换)
            await file.CopyAsync(storageFolder, "KnownFolder.jpg", NameCollisionOption.ReplaceExisting);
        }
示例#5
0
        private async void btnReadStream_Click(object sender, RoutedEventArgs e)
        {
            // 在指定的目录下获取指定的文件
            StorageFolder storageFolder = await KnownFolders.GetFolderForUserAsync(null, KnownFolderId.DocumentsLibrary);

            StorageFile storageFile = await storageFolder.GetFileAsync("webabcdStream.txt");

            if (storageFile != null)
            {
                using (IRandomAccessStream randomStream = await storageFile.OpenAsync(FileAccessMode.Read))
                {
                    using (DataReader dataReader = new DataReader(randomStream))
                    {
                        ulong size = randomStream.Size;
                        if (size <= uint.MaxValue)
                        {
                            // 从数据流中读取数据
                            uint numBytesLoaded = await dataReader.LoadAsync((uint)size);

                            // 将读取到的数据转换为字符串
                            string fileContent = dataReader.ReadString(numBytesLoaded);

                            lblMsg.Text = "读取结果:" + fileContent;
                        }
                    }
                }
            }
        }
        /// <summary>
        /// helper for all list by functions
        /// </summary>
        private async Task GroupByHelperAsync(QueryOptions queryOptions)
        {
            GroupedFiles.Clear();

            StorageFolder picturesFolder = await KnownFolders.GetFolderForUserAsync(null /* current user */, KnownFolderId.PicturesLibrary);

            StorageFolderQueryResult queryResult = picturesFolder.CreateFolderQueryWithOptions(queryOptions);

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

            foreach (StorageFolder folder in folderList)
            {
                IReadOnlyList <StorageFile> fileList = await folder.GetFilesAsync();

                var newList = new List <string>();

                newList.Add("Group: " + folder.Name + " (" + fileList.Count + ")");

                GroupedFiles.Add(newList);
                foreach (StorageFile file in fileList)
                {
                    newList.Add(file.Name);
                }
            }
        }
示例#7
0
        public async void testWritingFile()
        {
            //Uri myUri = new Uri("ms-appx:///file.txt");
            //StorageFile file = await StorageFile.GetFileFromApplicationUriAsync(myUri);



            StorageFolder storageFolder = await KnownFolders.GetFolderForUserAsync(null /* current user*/, KnownFolderId.PicturesLibrary);

            const string filename   = "SAMPLE.dat";
            StorageFile  sampleFile = null;

            try
            {
                sampleFile = await storageFolder.CreateFileAsync(filename, CreationCollisionOption.ReplaceExisting);

                var dialog = new MessageDialog(String.Format("The file '{0} was created.", sampleFile.Name));
                await dialog.ShowAsync();
            }
            catch (Exception ex)
            {
                // I/O errors are reported as exceptions.
                var dialog = new MessageDialog(String.Format("Error creating the file {0}: {1}", filename, ex.Message));
                await dialog.ShowAsync();
            }
        }
示例#8
0
        // 获取文件夹
        private async void btnGetFolder_Click(object sender, RoutedEventArgs e)
        {
            lblMsg.Text = "";

            // 获取当前用户的“图片库”的 StorageFolder 对象
            StorageFolder picturesFolder = await KnownFolders.GetFolderForUserAsync(null, KnownFolderId.PicturesLibrary);

            // 获取“图片库”所包含的全部文件夹
            IReadOnlyList <StorageFolder> folderList = await picturesFolder.GetFoldersAsync();

            foreach (StorageFolder storageFolder in folderList)
            {
                lblMsg.Text += "    " + storageFolder.Name;
                lblMsg.Text += Environment.NewLine;
            }


            // 在当前 StorageFolder 下获取指定名字的 StorageFolder,不存在的话会抛出 FileNotFoundException 异常
            try
            {
                await picturesFolder.GetFolderAsync("aabbcc");
            }
            catch (FileNotFoundException)
            {
                await new MessageDialog("在“图片库”中找不到名为“aabbcc”的文件夹").ShowAsync();
            }

            // 在当前 StorageFolder 下获取指定名字的 IStorageItem,不存在的话会也不会抛出 FileNotFoundException 异常,而是会返回 null
            IStorageItem item = await picturesFolder.TryGetItemAsync("aabbcc");

            if (item == null)
            {
                await new MessageDialog("在“图片库”中找不到名为“aabbcc”的文件夹或文件").ShowAsync();
            }
        }
示例#9
0
        // 获取文件夹和文件
        private async void btnGetFolderFile_Click(object sender, RoutedEventArgs e)
        {
            lblMsg.Text = "";

            // 获取当前用户的“图片库”的 StorageFolder 对象
            StorageFolder picturesFolder = await KnownFolders.GetFolderForUserAsync(null, KnownFolderId.PicturesLibrary);

            // 获取“图片库”所包含的全部文件夹和文件
            IReadOnlyList <IStorageItem> storageItems = await picturesFolder.GetItemsAsync();

            foreach (IStorageItem storageItem in storageItems)
            {
                if (storageItem.IsOfType(StorageItemTypes.Folder)) // 是文件夹
                {
                    StorageFolder storageFolder = storageItem as StorageFolder;
                    lblMsg.Text += "folder: " + storageFolder.Name;
                    lblMsg.Text += Environment.NewLine;
                }
                else if (storageItem.IsOfType(StorageItemTypes.File)) // 是文件
                {
                    StorageFile storageFile = storageItem as StorageFile;
                    lblMsg.Text += "file: " + storageFile.Name;
                    lblMsg.Text += Environment.NewLine;
                }
            }
        }
示例#10
0
        // 分组文件夹
        private async void btnFolderGroup_Click(object sender, RoutedEventArgs e)
        {
            lblMsg.Text = "";

            StorageFolder picturesFolder = await KnownFolders.GetFolderForUserAsync(null, KnownFolderId.PicturesLibrary);

            // 文件夹按月分组查询参数,其他多种分组方式请参见 CommonFolderQuery 枚举
            CommonFolderQuery folderQuery = CommonFolderQuery.GroupByMonth;

            // 判断一下 picturesFolder 是否支持指定的查询参数
            if (picturesFolder.IsCommonFolderQuerySupported(folderQuery))
            {
                // 创建查询
                StorageFolderQueryResult queryResult = picturesFolder.CreateFolderQuery(folderQuery);

                // 执行查询
                IReadOnlyList <StorageFolder> folderList = await queryResult.GetFoldersAsync();

                foreach (StorageFolder storageFolder in folderList) // 这里的 storageFolder 就是按月份分组后的月份文件夹(当然,物理上并没有月份文件夹)
                {
                    IReadOnlyList <StorageFile> fileList = await storageFolder.GetFilesAsync();

                    lblMsg.Text += storageFolder.Name + " (" + fileList.Count + ")";
                    lblMsg.Text += Environment.NewLine;
                    foreach (StorageFile file in fileList) // 月份文件夹内的文件
                    {
                        lblMsg.Text += "    " + file.Name;
                        lblMsg.Text += Environment.NewLine;
                    }
                }
            }
        }
示例#11
0
        // 新增一个下载任务
        private async void btnAddDownload_Click(object sender, RoutedEventArgs e)
        {
            Uri sourceUri = new Uri("http://files.cnblogs.com/webabcd/Windows10.rar", UriKind.Absolute);

            StorageFile destinationFile;

            try
            {
                // 保存的目标地址(别忘了在 Package.appxmanifest 中配置好 <Capability Name="documentsLibrary" /> 和 .rar 类型文件的关联)
                StorageFolder storageFolder = await KnownFolders.GetFolderForUserAsync(null, KnownFolderId.DocumentsLibrary);

                destinationFile = await storageFolder.CreateFileAsync("Windows10.rar", CreationCollisionOption.GenerateUniqueName);
            }
            catch (Exception ex)
            {
                WriteLine(ex.ToString());
                return;
            }

            BackgroundDownloader backgroundDownloader = new BackgroundDownloader();

            // 任务成功后弹出指定的 toast 通知(类似的还有 SuccessTileNotification, FailureToastNotification, FailureTileNotification)
            backgroundDownloader.SuccessToastNotification = GetToastNotification(sourceUri);
            // 创建一个后台下载任务
            DownloadOperation download = backgroundDownloader.CreateDownload(sourceUri, destinationFile);

            // 处理并监视指定的后台下载任务
            await HandleDownloadAsync(download, true);
        }
        private async void StartDownload_Click(object sender, RoutedEventArgs e)
        {
            // Reset the output whenever a new download attempt begins.
            DownloadedInfoText.Text   = "";
            DownloadedStatusText.Text = "";
            rootPage.NotifyUser("", NotifyType.StatusMessage);

            Uri source;

            if (!Uri.TryCreate(serverAddressField.Text.Trim(), UriKind.Absolute, out source))
            {
                rootPage.NotifyUser("Invalid URI.", NotifyType.ErrorMessage);
                return;
            }

            string destination = fileNameField.Text.Trim();

            if (string.IsNullOrWhiteSpace(destination))
            {
                rootPage.NotifyUser("A local file name is required.", NotifyType.ErrorMessage);
                return;
            }

            StorageFolder picturesLibrary = await KnownFolders.GetFolderForUserAsync(null /* current user */, KnownFolderId.PicturesLibrary);

            StorageFile destinationFile;

            try
            {
                destinationFile = await picturesLibrary.CreateFileAsync(destination, CreationCollisionOption.GenerateUniqueName);
            }
            catch (Exception ex)
            {
                rootPage.NotifyUser($"Error while creating file: {ex.Message}", NotifyType.ErrorMessage);
                return;
            }

            BackgroundDownloader downloader = new BackgroundDownloader();

            download = downloader.CreateDownload(source, destinationFile);

            // Opt into "random access" mode. Transfers configured this way have full support for resumable URL updates.
            // If the timestamp or file size of the updated URL is different from that of the previous URL, the download
            // will restart from scratch. Otherwise, the transfer will resume from the same position using the new URL.
            //
            // Due to OS limitations, downloads that don't opt into "random access" mode will always restart from scratch
            // whenever their URL is updated.
            download.IsRandomAccessRequired = true;

            if (configureRecoverableErrorsCheckBox.IsChecked.Value)
            {
                // Declare HTTP 403 (WebErrorStatus.Forbidden) as a recoverable error.
                download.RecoverableWebErrorStatuses.Add(WebErrorStatus.Forbidden);
            }

            DownloadedInfoText.Text = $"Downloading to {destinationFile.Name}, {download.Guid}";

            // Start the download and wait for it to complete.
            await HandleDownloadAsync();
        }
示例#13
0
        private async void CopyFileButton_Click(object sender, RoutedEventArgs e)
        {
            StorageFile file = rootPage.sampleFile;

            if (file != null)
            {
                try
                {
                    StorageFolder picturesLibrary = await KnownFolders.GetFolderForUserAsync(null /* current user */, KnownFolderId.PicturesLibrary);

                    StorageFile fileCopy = await file.CopyAsync(picturesLibrary, "sample - Copy.dat", NameCollisionOption.ReplaceExisting);

                    rootPage.NotifyUser(String.Format("The file '{0}' was copied and the new file was named '{1}'.", file.Name, fileCopy.Name), NotifyType.StatusMessage);
                }
                catch (FileNotFoundException)
                {
                    rootPage.NotifyUserFileNotExist();
                }
                catch (Exception ex)
                {
                    // I/O errors are reported as exceptions.
                    rootPage.NotifyUser(String.Format("Error copying file '{0}': {1}", file.Name, ex.Message), NotifyType.ErrorMessage);
                }
            }
            else
            {
                rootPage.NotifyUserFileNotExist();
            }
        }
示例#14
0
        private async Task WriteFileTxt(List <Point> list, string filename)
        {
            // create file
            StorageFolder storageFolder = await KnownFolders.GetFolderForUserAsync(null /* current user */, KnownFolderId.PicturesLibrary);

            try
            {
                StorageFile file = await storageFolder.CreateFileAsync(filename, CreationCollisionOption.ReplaceExisting);

                if (file != null)
                {
                    try
                    {
                        // string userContent = InputTextBox.Text;
                        //StatusMessage.Text = list.Count.ToString();
                        if (list.Count != 0)
                        {
                            String userContent = "";
                            for (int i = 0; i < list.Count; i++)
                            {
                                String line = String.Format("{0}, {1}, {2}, {3}, {4}, {5}", list.ElementAt(i).accX.ToString(),
                                                            list.ElementAt(i).accY.ToString(), list.ElementAt(i).accZ.ToString(), list.ElementAt(i).gyX.ToString(),
                                                            list.ElementAt(i).gyY.ToString(), list.ElementAt(i).gyZ.ToString());
                                userContent += line + Environment.NewLine;
                            }
                            await FileIO.WriteTextAsync(file, userContent);

                            // rootPage.NotifyUser(String.Format("The following text was written to '{0}':{1}{2}", file.Name, Environment.NewLine, userContent), NotifyType.StatusMessage);
                        }
                        else
                        {
                            StatusMessage.Text = "The list is empty, please collect something and then click 'Write' again.";
                        }
                    }
                    catch (FileNotFoundException)
                    {
                        StatusMessage.Text = "File not exit";
                    }
                    catch (Exception ex)
                    {
                        // I/O errors are reported as exceptions.
                        StatusMessage.Text = ex.Message;
                        // rootPage.NotifyUser(String.Format("Error writing to '{0}': {1}", file.Name, ex.Message), NotifyType.ErrorMessage);
                    }
                }
                else
                {
                    StatusMessage.Text = "File not exit";
                }
                // rootPage.NotifyUser(String.Format("The file '{0}' was created.", rootPage.sampleFile.Name), NotifyType.StatusMessage);
            }
            catch (Exception ex)
            {
                // I/O errors are reported as exceptions.
                // NotifyUser(String.Format("Error creating file '{0}': {1}", MainPage.filename, ex.Message), NotifyType.ErrorMessage);
                StatusMessage.Text = ex.Message;
            }
            // writefile
        }
        private async void CreateTestFile()
        {
            StorageFolder folder = await KnownFolders.GetFolderForUserAsync(null /* current user */, KnownFolderId.PicturesLibrary);

            await folder.CreateFileAsync("Test " + Extension + " file." + Extension, CreationCollisionOption.ReplaceExisting);

            await Windows.System.Launcher.LaunchFolderAsync(folder);
        }
示例#16
0
        private async void CreateFileButton_Click(object sender, RoutedEventArgs e)
        {
            StorageFolder storageFolder = await KnownFolders.GetFolderForUserAsync(null /* current user */, KnownFolderId.PicturesLibrary);

            rootPage.sampleFile = await storageFolder.CreateFileAsync(MainPage.filename, CreationCollisionOption.ReplaceExisting);

            rootPage.NotifyUser(String.Format("The file '{0}' was created.", rootPage.sampleFile.Name), NotifyType.StatusMessage);
        }
 private async Task<IStorageFile> CreateResultFileAsync(int id)
 {
     StorageFolder picturesLibrary = await KnownFolders.GetFolderForUserAsync(null /* current user */, KnownFolderId.PicturesLibrary);
     IStorageFile resultFile = await picturesLibrary.CreateFileAsync(
         String.Format(CultureInfo.InvariantCulture, "picture{0}.png", id),
         CreationCollisionOption.GenerateUniqueName);
     return resultFile;
 }
示例#18
0
        // Create Folder
        private async void CreateFolder()
        {
            StorageFolder picturesFolder = await KnownFolders.GetFolderForUserAsync(null, KnownFolderId.PicturesLibrary);

            _myFolder = await picturesFolder.CreateFolderAsync("MyFolder", CreationCollisionOption.OpenIfExists);

            // Tips: Another alternative way
            // _myFolder = await picturesFolder.CreateFolderAsync(@"MyFolder\sub\subsub", CreationCollisionOption.OpenIfExists);
        }
示例#19
0
        public async Task <List <Point> > ReadFileTxt(string filename)
        {
            //string fullPath = Path.GetFullPath(filename);
            string[]      lines;
            string        content;
            List <Point>  model           = new List <Point>();
            StorageFolder picturesLibrary = await KnownFolders.GetFolderForUserAsync(null /* current user */, KnownFolderId.PicturesLibrary);

            StorageFile file = (StorageFile)await picturesLibrary.TryGetItemAsync(filename);

            if (file == null)
            {
                // If file doesn't exist, indicate users to use scenario 1
                // NotifyUser(String.Format("The file '{0}' does not exist. Use scenario one to create this file.", filename), NotifyType.ErrorMessage);
                StatusMessage.Text = "File not found";
            }
            else
            {
                try
                {
                    StatusMessage.Text = "reading";
                    content            = await FileIO.ReadTextAsync(file);

                    // StatusMessage.Text = "1";
                    lines = content.Split('\n');
                    // StatusMessage.Text = "2";
                    for (int i = 0; i < lines.Count(); i++)
                    {
                        string[] args     = lines[i].Split(',', ' ', '\t');
                        Point    newPoint = new Point();
                        //newPoint.accX = Double.Parse(args[0]);
                        //newPoint.accY = Double.Parse(args[1]);
                        //newPoint.accZ = Double.Parse(args[2]);
                        //newPoint.gyX = Double.Parse(args[3]);
                        //newPoint.gyY = Double.Parse(args[4]);
                        //newPoint.gyZ = Double.Parse(args[5]);
                        newPoint.setAccelerometter(double.Parse(args[0], CultureInfo.InvariantCulture), double.Parse(args[1], CultureInfo.InvariantCulture), double.Parse(args[2], CultureInfo.InvariantCulture));
                        newPoint.setGyroscope(double.Parse(args[3], CultureInfo.InvariantCulture), double.Parse(args[4], CultureInfo.InvariantCulture), double.Parse(args[5], CultureInfo.InvariantCulture));
                        model.Add(newPoint);
                    }
                    //  StatusMessage.Text = "3";
                }
                catch (FileNotFoundException)
                {
                    //rootPage.NotifyUserFileNotExist();
                    StatusMessage.Text = "File not found";
                }
                catch (Exception ex)
                {
                    // I/O errors are reported as exceptions.
                    //rootPage.NotifyUser(String.Format("Error reading from '{0}': {1}", file.Name, ex.Message), NotifyType.ErrorMessage);
                    StatusMessage.Text = ex.Message;
                }
            }
            return(model);
        }
示例#20
0
        // 创建文件夹
        private async void btnCreateFolder_Click(object sender, RoutedEventArgs e)
        {
            StorageFolder picturesFolder = await KnownFolders.GetFolderForUserAsync(null, KnownFolderId.PicturesLibrary);

            _myFolder = await picturesFolder.CreateFolderAsync("MyFolder", CreationCollisionOption.OpenIfExists);

            // 创建文件夹时也可以按照下面这种方式创建多级文件夹
            // _myFolder = await picturesFolder.CreateFolderAsync(@"MyFolder\sub\subsub", CreationCollisionOption.OpenIfExists);

            lblMsg.Text = "创建了文件夹";
        }
示例#21
0
        protected async override void OnNavigatedTo(NavigationEventArgs e)
        {
            // 获取“图片库”目录下的所有根文件
            StorageFolder picturesFolder = await KnownFolders.GetFolderForUserAsync(null, KnownFolderId.PicturesLibrary);

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

            listBox.ItemsSource = fileList.Select(p => p.Name).ToList();

            base.OnNavigatedTo(e);
        }
        /// <summary>
        /// Checks if sample file already exists, if it does assign it to sampleFile
        /// </summary>
        internal async void ValidateFile()
        {
            StorageFolder picturesLibrary = await KnownFolders.GetFolderForUserAsync(null /* current user */, KnownFolderId.PicturesLibrary);

            sampleFile = (await picturesLibrary.TryGetItemAsync(filename)) as StorageFile;
            if (sampleFile == null)
            {
                // If file doesn't exist, indicate users to use scenario 1
                NotifyUserFileNotExist();
            }
        }
示例#23
0
        private async void listBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            // 用户选中的文件
            string        fileName       = (string)listBox.SelectedItem;
            StorageFolder picturesFolder = await KnownFolders.GetFolderForUserAsync(null, KnownFolderId.PicturesLibrary);

            StorageFile storageFile = await picturesFolder.GetFileAsync(fileName);

            // 显示文件的缩略图
            await ShowThumbnail(storageFile);
        }
示例#24
0
        protected async override void OnNavigatedTo(NavigationEventArgs e)
        {
            // 获取全部可移动存储
            StorageFolder removableDevices = await KnownFolders.GetFolderForUserAsync(null, KnownFolderId.RemovableDevices);

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

            listBox.ItemsSource = folderList.Select(p => p.Name).ToList();

            base.OnNavigatedTo(e);
        }
示例#25
0
        private async void btnWriteText_Click(object sender, RoutedEventArgs e)
        {
            // 在指定的目录下创建指定的文件
            StorageFolder storageFolder = await KnownFolders.GetFolderForUserAsync(null, KnownFolderId.DocumentsLibrary);

            StorageFile storageFile = await storageFolder.CreateFileAsync("webabcdText.txt", CreationCollisionOption.ReplaceExisting);

            // 在指定的文件中写入指定的文本
            string textContent = "I am webabcd";
            await FileIO.WriteTextAsync(storageFile, textContent, Windows.Storage.Streams.UnicodeEncoding.Utf8); // 编码为 UnicodeEncoding.Utf8

            lblMsg.Text = "写入成功";
        }
示例#26
0
        private async void listBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            // 用户选中的文件夹
            string        folderName     = (string)listBox.SelectedItem;
            StorageFolder picturesFolder = await KnownFolders.GetFolderForUserAsync(null, KnownFolderId.PicturesLibrary);

            StorageFolder storageFolder = await picturesFolder.GetFolderAsync(folderName);

            // 显示文件夹的各种属性
            ShowProperties1(storageFolder);
            await ShowProperties2(storageFolder);
            await ShowProperties3(storageFolder);
        }
示例#27
0
        protected async override void OnNavigatedTo(NavigationEventArgs e)
        {
            // 在指定的目录下创建指定的文件
            StorageFolder documentsFolder = await KnownFolders.GetFolderForUserAsync(null, KnownFolderId.DocumentsLibrary);

            StorageFile storageFile = await documentsFolder.CreateFileAsync("webabcdCacheAccess.txt", CreationCollisionOption.ReplaceExisting);

            // 在指定的文件中写入指定的文本
            string textContent = "I am webabcd";
            await FileIO.WriteTextAsync(storageFile, textContent, Windows.Storage.Streams.UnicodeEncoding.Utf8);

            base.OnNavigatedTo(e);
        }
示例#28
0
        private async void listBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            // 用户选中的可移动存储
            string        folderName       = (string)listBox.SelectedItem;
            StorageFolder removableDevices = await KnownFolders.GetFolderForUserAsync(null, KnownFolderId.RemovableDevices);

            StorageFolder storageFolder = await removableDevices.GetFolderAsync(folderName);

            // 用户选中的可移动存储中的根目录下的文件和文件夹总数
            IReadOnlyList <IStorageItem> storageItems = await storageFolder.GetItemsAsync();

            lblMsg.Text = "items count: " + storageItems.Count;
        }
示例#29
0
        private async void btnWriteBinary_Click(object sender, RoutedEventArgs e)
        {
            // 在指定的目录下创建指定的文件
            StorageFolder storageFolder = await KnownFolders.GetFolderForUserAsync(null, KnownFolderId.DocumentsLibrary);

            StorageFile storageFile = await storageFolder.CreateFileAsync("webabcdBinary.txt", CreationCollisionOption.ReplaceExisting);

            // 将字符串转换成二进制数据,并保存到指定文件
            string  textContent = "I am webabcd";
            IBuffer buffer      = ConverterHelper.String2Buffer(textContent);
            await FileIO.WriteBufferAsync(storageFile, buffer);

            lblMsg.Text = "写入成功";
        }
示例#30
0
        private async void playSound(String name)
        {
            MediaElement PlayMusic = new MediaElement();
            // StorageFolder Folder = Windows.ApplicationModel.Package.Current.InstalledLocation;
            StorageFolder storageFolder = await KnownFolders.GetFolderForUserAsync(null, KnownFolderId.PicturesLibrary);

            //Folder = await Folder.GetFolderAsync("MyFolder");
            //StorageFile sf = await Folder.GetFileAsync("aaa.mp3");
            StorageFile sf = await storageFolder.TryGetItemAsync(name) as StorageFile;

            //oof.mp3 is in Pictures
            PlayMusic.SetSource(await sf.OpenAsync(FileAccessMode.Read), sf.ContentType);
            PlayMusic.Play();
        }