【问题标题】:how to read a text file in windows universal app如何在 Windows 通用应用程序中读取文本文件
【发布时间】:2016-01-04 00:38:40
【问题描述】:

我正在尝试读取名为 thedata.txt 的文本文件,其中包含我想在刽子手游戏中使用的单词列表。我尝试了不同的方法,但我无法确定文件的放置位置,如果在应用程序运行时根本无法确定的话。我将文件添加到我的项目中,我尝试将构建属性设置为内容,然后嵌入资源,但找不到文件。我制作了一个 Windows 10 通用应用程序项目。我试过的代码是这样的:

  Stream stream = this.GetType().GetTypeInfo().Assembly.GetManifestResourceStream("thedata.txt");
            using (StreamReader inputStream = new StreamReader(stream))
            {
                while (inputStream.Peek() >= 0)
                {
                    Debug.WriteLine("the line is ", inputStream.ReadLine());
                }
            }

我得到了例外。 我还尝试列出另一个目录中的文件:

 string path = Windows.Storage.ApplicationData.Current.LocalFolder.Path;
            Debug.WriteLine("The path is " + path);
            IReadOnlyCollection<StorageFile> files = await Windows.Storage.ApplicationData.Current.LocalFolder.GetFilesAsync();
            foreach (StorageFile file2 in files)
            {
                Debug.WriteLine("Name 2 is " + file2.Name + ", " + file2.DateCreated);
            }

我在那里也看不到文件...我想避免在我的程序中对名称列表进行硬编码。我不确定该文件的放置路径。

【问题讨论】:

    标签: c# windows-10-universal windows-10-mobile


    【解决方案1】:

    代码非常简单,您只需使用有效的方案 URI(在您的情况下为 ms-appx)并将您的 WinRT InputStream 转换为经典的 .NET 流:

    var file = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///thedata.txt"));
    using (var inputStream = await file.OpenReadAsync())
    using (var classicStream = inputStream.AsStreamForRead())
    using (var streamReader = new StreamReader(classicStream))
    {
        while (streamReader.Peek() >= 0)
        {
            Debug.WriteLine(string.Format("the line is {0}", streamReader.ReadLine()));
        }
    }
    

    对于嵌入文件的属性,“构建操作”必须设置为“内容”,“复制到输出目录”应设置为“不复制”。

    【讨论】:

    • t.ouvre 提供的上述代码回答了我的问题。我已经验证它可以在我的电脑和模拟器上运行。感谢您回答我的问题。
    • 像魅力一样工作。谢谢
    【解决方案2】:

    您不能在 Windows 运行时应用中使用经典的 .NET IO 方法,在 UWP 中读取文本文件的正确方法是:

    var file = await ApplicationData.Current.LocalFolder.GetFileAsync("data.txt");
    var lines = await FileIO.ReadLinesAsync(file);
    

    此外,您不需要文件夹的物理路径 - 来自 msdn

    不要依赖这个属性来访问文件夹,因为文件系统 某些文件夹的路径不可用。例如,在下面 情况下,文件夹可能没有文件系统路径,或者文件系统 路径可能不可用。 •文件夹代表一个容器 文件组(例如,某些重载的返回值 GetFoldersAsync 方法)而不是文件中的实际文件夹 系统。 •文件夹由URI 支持。 •文件夹被选中 使用文件选择器。

    【讨论】:

      【解决方案3】:

      详情请参考File access permissionsCreate, write, and read a file 提供了与 Windows 10 上 UWP 应用的文件 IO 相关的示例。

      您可以使用应用 URI 直接从应用的本地文件夹中检索文件,如下所示:

      using Windows.Storage;
      
      StorageFile file = await StorageFile.GetFileFromApplicationUriAsync("ms-appdata:///local/file.txt");  
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-10-03
        • 2016-02-12
        • 1970-01-01
        • 2014-01-10
        • 1970-01-01
        相关资源
        最近更新 更多