在 UWP 中创建文件和文件夹 [英] Creating Files and Folders in UWP

查看:61
本文介绍了在 UWP 中创建文件和文件夹的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看了这么多stackoverflow帖子和文章,但仍然没有设法在UWP中创建文件.在 WPF 中,这真的很容易,但 UWP 的工作方式不同.

Ive looked at at so many stackoverflow posts and articles but still didnt manage to create a file in UWP. In WPF it was really easy but UWP works differently.

我在清单文件中添加了以下内容:

I added the following in my manifest file:

  <Capabilities>
    <uap:Capability Name="documentsLibrary" />
  </Capabilities>

现在我不确定下一步该怎么做.在我的文档文件夹中,我有一个名为项目文件"的子文件夹.我想在那里创建文件夹和文件.这是如何在 UWP 中完成的?我真的不明白.

Now im not sure what to do next. Inside my documents folder I have a subfolder named "Project Files". I want to create folders and files in there. How is this done in UWP? I really dont understand.

推荐答案

正如 microsoft 在他们的文档中所说,它建议不要通过 UWP 应用程序使用文档库,而是选择内置存储,除非绝对必要.

As microsoft states in their docs, its recommenced not to use the documents Library through an UWP app, instead opt for the built in storage unless its absolutely necessary.

如果您使用文件夹选择器,有一种简单的方法可以解决这个问题

There is an easy way to get around that if you use a folder picker

 private async void buttonClick(){
            FolderPicker folderPicker = new FolderPicker();
     folderPicker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;
      folderPicker.FileTypeFilter.Add("*");

          StorageFolder folder=  await folderPicker.PickSingleFolderAsync();
         if (folder != null) { 

              //  do Things On Folder

          }
           else
          {
              MessageDialog dialog = new MessageDialog("you selected nothing");
             await dialog.ShowAsync();
          }

}

上面打开了一个文件夹选择对话框,它返回用户选择的文件夹,这是访问应用程序文件夹外位置的推荐方式.

The above opens up a folder select dialog, it returns the folder the user picked, its the recommended way for accessing locations outside your app's folder.

以下是在此文件夹中创建新文件的方法:

Here is how to Create a new file in this folder:

string name ="myTitle.txt";
            await folder.CreateFileAsync(name, CreationCollisionOption.GenerateUniqueName);

这里是如何打开和写入文件:

here is how to open and write a file:

         try {
                           StorageFile myFile = await folder.GetFileAsync(name);
                           await Windows.Storage.FileIO.WriteTextAsync(myFile,  "myStringContent");

                               }
                       catch (Exception e)
                       {
                           Debug.WriteLine("Failure: "+e.Message);

                           return;
                       }

请记住,如果您使用本地存储,则始终可以避免打开对话框,它会在一行中返回应用程序的存储文件夹,如下所示:

remember you can always avoid opening up a dialog if you use the local storage instead, it returns you app's storage folder in one line, like this:

 var folder= ApplicationData.Current.LocalFolder;

这篇关于在 UWP 中创建文件和文件夹的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆