【问题标题】:System.IO.FileNotFoundException: 'Could not find file "/mytextfile.txt"' in xamarin formsSystem.IO.FileNotFoundException:'在 xamarin 表单中找不到文件“/mytextfile.txt”'
【发布时间】:2020-08-05 17:51:53
【问题描述】:

List mytext = new List();

mytext= File.ReadAllLines(@"mytextfile.txt").ToList();

我有一个文件 mytextfile.txt,我把它放在项目的文件夹中。然后我试图读取这个文件,但我得到错误,它找不到我的文件

System.IO.FileNotFoundException: '找不到文件“/mytextfile.txt”

【问题讨论】:

标签: c# xamarin xamarin.forms


【解决方案1】:

"/mytextfile.txt" 这意味着将从可执行文件的当前目录读取文件。将文件复制到您的outdir。它将能够找到它。或者给出一个完整的物理路径,例如"D:\sample\xamarinapp"

【讨论】:

  • 如果文件有误,我会将文件复制到 assets 文件夹中。我应该把文件放在哪里?
  • 仅当您愿意时才将文件保存在 assets 文件夹中。然后,您可以通过右键单击文件并在属性选项中选择“始终复制”来使其始终复制到输出
  • 另一种方法是在项目属性的 Pre-Build 事件中添加复制命令,将文件复制到 $(OutDir) 即输出文件夹
  • 我这样做了,总是复制,但它不起作用。我又得到了那个错误
【解决方案2】:

System.IO 类可用于访问每个平台上的文件系统。

所以如果你想使用File.ReadAllLines,它将访问你设备的文件系统,而不是Assets文件夹。

您可以尝试将您的mytextfile.txt 移动到您的PCL 项目,并将其Build Action 设置为EmbeddedResource

然后像这样访问它:

public partial class MainPage: ContentPage
{
    public MainPage()
    {
        InitializeComponent();
        var assembly = IntrospectionExtensions.GetTypeInfo(typeof(MainPage)).Assembly;
        Stream stream = assembly.GetManifestResourceStream("your namespace.mytextfile.txt");
        string text = "";
        using (var reader = new System.IO.StreamReader(stream))
         {
           text = reader.ReadToEnd();
         }
   }
}

更多可以参考this

【讨论】:

    猜你喜欢
    • 2021-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-22
    • 1970-01-01
    • 2022-12-01
    • 2019-07-01
    • 1970-01-01
    相关资源
    最近更新 更多