UWP从字符串中的(from)文件夹中写入(和读取)文件

时间:2016-10-19 12:18:41

标签: c# uwp

我正在为桌面开发UWP应用程序。用户可以在设置页面中选择要创建一些文件和文件夹的位置。通常我使用StreamWriter之类的:

using (System.IO.StreamWriter file = new System.IO.StreamWriter(path)) {
    file.WriteLine("Something");
}

我尝试使用StorageFolder

StorageFolder folder = ApplicationData.Current.LocalFolder;

但我找不到从C:\MyFolder等字符串中指定文件夹的方法。

提前谢谢。

2 个答案:

答案 0 :(得分:3)

您可以让用户使用FolderPicker类指定他想要的文件夹。

var folderPicker = new Windows.Storage.Pickers.FolderPicker();
folderPicker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.Desktop;
Windows.Storage.StorageFolder folder = await folderPicker.PickSingleFolderAsync();
if (folder != null)
{
    // Application now has read/write access to all contents in the picked folder
    // (including other sub-folder contents)
    Windows.Storage.AccessCache.StorageApplicationPermissions.FutureAccessList.AddOrReplace("PickedFolderToken", folder);

    //<<Here, you can write your files in the selected folder.>>

}
else
{
    //Operation cancelled.
}

您可以找到有关如何使用它的更多信息here

答案 1 :(得分:1)

不幸的是,目前无法避免与用户的交互。在我看来,这很奇怪,但就是这样。

然后,当用户选择了一个文件夹时,所有应用程序都可以使用该文件夹。文档不清楚我们如何使用所有功能。在以下代码中,您可以找到如何实现它的示例。如果代码错误或我可以改进,请告诉我。

/// <summary>
/// Picks a folder.
/// </summary>
public async void PickFolder() {
    var folderPicker = new Windows.Storage.Pickers.FolderPicker();
    folderPicker.SuggestedStartLocation = 
        Windows.Storage.Pickers.PickerLocationId.Desktop;

    // unless you want to open a folder, FileTypeFilter is required
    folderPicker.FileTypeFilter.Add(".cs");
    folderPicker.FileTypeFilter.Add(".jpg");

    Windows.Storage.StorageFolder folder = await folderPicker.PickSingleFolderAsync();
    if (folder != null) {
        // Application now has read/write access to all contents in the picked folder
        // (including other sub-folder contents)
        Windows.Storage.AccessCache.StorageApplicationPermissions.
            FutureAccessList.AddOrReplace("PickedFolderToken", folder);

        StorageFolder mainFolder = await folder.CreateFolderAsync("Generator");
        await mainFolder.CreateFolderAsync("Code");
        await mainFolder.CreateFolderAsync("EventsArgs");

        StorageFolder newFolder = 
                  await CreateFileInANewFolder(mainFolder, "MyFolder", "MyCode.cs",
                      new List<string>() { "My code line 1", "My code line 2" });
        List<string> fileLines = await ReadFile(newFolder, "MyCode.cs");

        StorageFile file = 
            await mainFolder.CreateFileAsync("Code.cs", 
                                             CreationCollisionOption.ReplaceExisting);
        List<string> lines = new List<string>() { 
                 "Hello world!", "This is a second line" 
        };

        await FileIO.WriteLinesAsync(file, lines);
    }
    else {
        // the user didn't select any folder
    }
}

另一个函数接收文件夹引用并创建文件夹和文件。

/// <summary>
/// Creates the file in a new folder.
/// </summary>
/// <param name="folder">The folder.</param>
/// <param name="newFolder">The new folder.</param>
/// <param name="filename">The filename.</param>
/// <param name="lineContent">Content of the line.</param>
/// <returns>Task&lt;StorageFolder&gt;.</returns>
public async Task<StorageFolder> CreateFileInANewFolder(
    StorageFolder folder, string newFolder, string filename, List<string> lineContent) {
    StorageFolder myFolder = await folder.CreateFolderAsync(newFolder);
    StorageFile file = await myFolder.CreateFileAsync(filename, 
                       CreationCollisionOption.ReplaceExisting);
    await FileIO.WriteLinesAsync(file, lineContent);

    return myFolder;
}

此功能从文件夹中读取文件。

/// <summary>
/// Reads the file.
/// </summary>
/// <param name="folder">The folder.</param>
/// <param name="filename">The filename.</param>
/// <returns>Task&lt;List&lt;System.String&gt;&gt;.</returns>
public async Task<List<string>> ReadFile(StorageFolder folder, string filename) {
    StorageFile file = await folder.GetFileAsync(filename);
    IList<string> lines = await FileIO.ReadLinesAsync(file);
    return lines.ToList();
}

为此,您必须添加以下using

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Windows.Storage;
using Windows.UI.Xaml.Controls;

当用户选择包含PickFolder的文件夹时,此功能会在名为Generator的下方创建一个文件夹,并在其他两个名为CodeEventsArgs的文件夹下创建。

然后调用CreateFileInANewFolder。此函数的参数为​​所选文件夹的StorageFolder,此函数会在新文件下创建一个新文件夹。

ReadFile读取使用CreateFileInANewFolder创建的文件并返回行。

我希望这个例子可以帮助别人。