【问题标题】:Read file in C# Console Project works but not for App Project in Visual Studio在 C# 控制台项目中读取文件有效,但不适用于 Visual Studio 中的 App 项目
【发布时间】:2018-09-03 10:24:46
【问题描述】:

按照以下步骤:

  • 新解决方案 > 其他 > .NET > 控制台项目

  • 项目 > 添加文件 > 路径/to/myfile.txt

  • myfile.txt > 构建操作 > EmbeddedResource

  • myfile.txt > 快捷属性 > 复制到输出目录

这就是Program.cs 的样子:

namespace Program
{
    class MainClass
    {
        public static void Main(string[] args)
        {
            string text = System.IO.File.ReadAllText("myfile.txt");
        }
    }
}

这个构建没有错误。

例如,当我创建一个 Android 应用程序(New Solution > Android > App) 并重复所有与之前相同的步骤,然后尝试构建:

namespace Program
{
    [Activity(Label = "Program", MainLauncher = true, Icon = "@mipmap/icon")]
    public class MainActivity : Activity
    {

        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            string text = System.IO.File.ReadAllText("myfile.txt");
        }
    }
}

我得到了错误:

System.IO.FileNotFoundException 已被抛出

找不到文件“/myfile.txt”

对于跨平台应用程序项目,是否有任何其他必要步骤来确保文本文件在构建过程中可用?

【问题讨论】:

    标签: c# xamarin


    【解决方案1】:

    Android 的行为方式与 Windows 控制台应用程序不同。要在 Android 中实现类似的功能,请使用 Asset

    使用 Android Asset

    的构建操作将文件添加到 Assets 文件夹
    // Read the contents of our asset
    string content;
    AssetManager assets = this.Assets;
    using (StreamReader sr = new StreamReader (assets.Open ("read_asset.txt")))
    {
        content = sr.ReadToEnd ();
    }
    

    【讨论】:

    • 谢谢,这行得通。我可以在 iOS 方面使用 string path = Foundation.NSBundle.MainBundle.PathForResource("myfile", "txt", "Assets"); text = System.IO.File.ReadAllText(path);
    • 我知道这不会那么难,但我必须高高在上 3 天才能找到它。谢谢你!!我在 C# 项目中这样做,所以我不得不更改这一行 AssetManager assets = Android.App.Application.Context.Assets;
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-08-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-28
    • 1970-01-01
    相关资源
    最近更新 更多