【问题标题】:How to access StorageFile from another method如何从另一种方法访问 StorageFile
【发布时间】:2015-12-20 02:40:22
【问题描述】:

所以我制作了一个 Windows 商店应用程序,您可以通过文件选择器使用一个按钮选择一个文件,然后使用另一个按钮处理该文件,但我无法将所选文件用于处理方法。
由于选取器将我的文本块之一设置为要为我尝试使用的用户显示的文件路径:
StorageFile file = await StorageFile.GetFileFromPathAsync(fullFilePath.Text);
但是由于 Windows RT 的限制,我只能从大多数位置拒绝访问它
关于尝试什么的任何其他建议?

第一个按钮点击:

private async Task getFile()
        {
            FileOpenPicker openPicker = new FileOpenPicker();
            openPicker.ViewMode = PickerViewMode.List;
            openPicker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;
            openPicker.FileTypeFilter.Add(".txt");

            StorageFile file = await openPicker.PickSingleFileAsync();
            if (file != null)
            {
                fullFilePath.Text = file.Path;
            }
            else
            {
                updateStatus("File Selection cancelled.");
            }
        }

第二个按钮启动这个但需要使用上面的文件

private async Task processFile()
{
    ...
    string content = await FileIO.ReadTextAsync(file);
    ...
}

【问题讨论】:

  • Call file from another method 的可能重复项
  • @chue 啊,感谢您阅读全文
  • 旁注:作为一般规则,您应该避免在通用 Windows 应用程序中使用文件路径进行编程 - 它们的主要(唯一?)用途是传递给采用文件路径的 Win32 函数,或者可能显示给用户。您永远不应该在任何地方保存文件路径并期望它再次工作(甚至是您自己数据的路径)。
  • @PeterTorr-MSFT 是的,我想通了,但我不知道如何在不按顺序调用的情况下将 StorageFile 文件传递​​给其他方法,显示路径的主要原因是用户可以看到它
  • 最简单的方法是让 StorageFile 成为类中的字段而不是局部变量

标签: c# windows windows-runtime microsoft-metro


【解决方案1】:

StorageFile 设为班级中的一个字段:

class MyClass
{
  StorageFile m_pickedFile;

  async Task GetFile()
  {
    // Setup the picker...
    m_pickedFile = await openPicker.PickSingleFileAsync();

    // Show the path to the user...
  }

  async Task ProcessFile()
  {
    if (m_pickedFile != null)
    {
      // now use m_pickedFile...
    }
  }
}

【讨论】:

    猜你喜欢
    • 2023-04-05
    • 1970-01-01
    • 2020-06-16
    • 2021-09-18
    • 1970-01-01
    • 2020-02-20
    • 2019-07-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多