C#控制台项目中的读取文件可以工作,但Visual Studio中的应用程序项目不能
遵循以下步骤:C#控制台项目中的读取文件可以工作,但Visual Studio中的应用程序项目不能,c#,xamarin,C#,Xamarin,遵循以下步骤: 新解决方案>其他>.NET>控制台项目 项目>添加文件>路径/to/myfile.txt myfile.txt>构建操作>嵌入资源 myfile.txt>快速属性>复制到输出目录 这就是Program.cs的外观: namespace Program { class MainClass { public static void Main(string[] args) { string text =
- 新解决方案>其他>.NET>控制台项目
- 项目>添加文件>路径/to/myfile.txt
- myfile.txt>构建操作>嵌入资源
- myfile.txt>快速属性>复制到输出目录
Program.cs
的外观:
namespace Program
{
class MainClass
{
public static void Main(string[] args)
{
string text = System.IO.File.ReadAllText("myfile.txt");
}
}
}
这是一个没有错误的构建
例如,当我创建一个安卓应用程序(新解决方案>安卓>应用程序)并重复所有与之前相同的步骤,然后尝试构建:
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”
对于跨平台应用程序项目,是否有其他必要的步骤来确保文本文件在构建过程中可用?Android与windows控制台应用程序的行为方式不同。要在Android中实现类似的功能,请使用 使用Android Asset的构建操作将文件添加到Assets文件夹
谢谢,行得通。我可以使用<代码> String PATH=Base.NSbop.MeNetry.PathForResource(“MyFrase'”、“TXT”、“资产”);text=System.IO.File.ReadAllText(路径)代码>对于iOS方面的事情。我知道这不会那么难,但我必须在3天内到处寻找才能找到这个。非常感谢。我在C#项目中这样做,所以我不得不更改这一行
AssetManager assets=Android.App.Application.Context.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 ();
}