gpt4 book ai didi

c# - 尝试使用带有 Xamarin Forms 的 StreamReader 从文件中读取时值为 "null"

转载 作者:太空宇宙 更新时间:2023-11-03 22:46:46 26 4
gpt4 key购买 nike

所以我试图让我的代码从文件中读取文本并将其显示在 ScrollView 中,顶部有一个固定标签。想一想电子阅读器,书名固定在屏幕顶部,但内容滚动。我从 Xamarin 网站下载的“使用 Xamarin 创建移动应用程序”一书中的示例中逐字复制了文本。但是,当我运行我的代码时,没有显示任何文本;屏幕只显示空白,就好像应用程序正在模拟器上运行,但没有分配代码。使用 Visual Studio 的调试器,我进入代码并意识到,由于某种原因,变量“stream”没有被赋值——根据调试器,它的值为 null,这导致“值不能为 null” “异常(exception)。这只是我尝试使用 Xamarin Forms 编写的第二个代码,使用这本书作为模板,我只是对为什么没有为“流”赋值感到困惑。希望你们中的一位可爱的人可以帮助我!

如果查看我引用的代码会有所帮助,可以在可从 Microsoft 下载的书中找到 here ,在 PDF 的第 105-106 页(或第 84-85 页,如果您要查看本书的页码)。

我尝试过的事情:

  • 我使用了 assembly.GetManifestResourceNames() 来确保我输入的资源 ID 是正确的。我最初将它作为“ereader.Texts.JP.txt”,因为程序本身称为 cdern_lab10,我认为那是命名空间。但是,GetManifestResourceNames() 返回“JP.Texts.JP.txt”,所以我更改了它。
  • 我已经仔细检查以确保该资源被标记为嵌入资源,事实确实如此。我还删除并重新添加了资源,并再次检查以确保它已嵌入。它存储在项目中名为“Texts”的文件夹中。

注意:大约一年前(here)在这里提出了一个类似的问题,但似乎从未真正得到回答。

using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Text;
using Xamarin.Forms;

namespace ereader
{
class TextPage : ContentPage
{
public TextPage()
{
StackLayout mainStack = new StackLayout();
StackLayout textStack = new StackLayout
{
Padding = new Thickness(5),
Spacing = 10
};

Assembly assembly = GetType().GetTypeInfo().Assembly;
string resource = "JP.Texts.JP.txt";

using (Stream stream = assembly.GetManifestResourceStream(resource))
{
using (StreamReader reader = new StreamReader (stream))
{
bool gotTitle = false;
string line;
while (null != (line = reader.ReadLine()))
{
Label label = new Label
{
Text = line,
TextColor = Color.Black
};

if (!gotTitle)
{
label.HorizontalOptions = LayoutOptions.Center;
label.FontSize = Device.GetNamedSize(NamedSize.Medium, label);
label.FontAttributes = FontAttributes.Bold;
mainStack.Children.Add(label);
gotTitle = true;
}
else
{
textStack.Children.Add(label);
}
}
}
}

ScrollView scrollView = new ScrollView
{
Content = textStack,
VerticalOptions = LayoutOptions.FillAndExpand,
Padding = new Thickness(5, 0),
};

mainStack.Children.Add(scrollView);
Content = mainStack;
BackgroundColor = Color.White;
Padding = new Thickness(0, 0, 0, 0);
}
}
}

最佳答案

你可以尝试这样的事情:

var assembly = IntrospectionExtensions.GetTypeInfo(typeof(TextPage)).Assembly;
Stream stream = assembly.GetManifestResourceStream("JP.Texts.JP.txt");
string text = "";
using (var reader = new System.IO.StreamReader (stream)) {
text = reader.ReadToEnd ();
}
Debug.WriteLine(text);

删除您的 bin 和 obj 文件夹并重建。

这是处理嵌入式资源的文档链接: https://learn.microsoft.com/en-us/xamarin/xamarin-forms/app-fundamentals/files?tabs=vsmac

关于c# - 尝试使用带有 Xamarin Forms 的 StreamReader 从文件中读取时值为 "null",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49480863/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com