I have data.txt file in my project file explorer. I want to read data from this text file, but every time I try it, the result comes null and the program crashes. The code I wrote is :
public MapPage()
{
var assembly = typeof(MapPage).GetTypeInfo().Assembly;
Stream stream = assembly.GetManifestResourceStream("Mapper.data.txt");
string text = "";
using (var reader = new System.IO.StreamReader(stream))
{
text = reader.ReadToEnd();
}
}
Using this code block, the stream always comes null. Here is the project file explorer :
I select the text file as Embedded Resource from its properties.
As pointed out via the documentation referenced below, the code you have is for a PCL/.NET Standard project. If you are using a Shared Project type then you must target the device type via a prefix, i.e. Mapper.IOS, Mapper.Droid, etc.
I have tested both scenarios and they do work using the same code you have in your question, but using the prefixes for IOS, Droid, etc. in the Shared Project type.
public MainPage()
{
#if __IOS__
var resourcePrefix = "Mapper.iOS";
#endif
#if __ANDROID__
var resourcePrefix = "Mapper.Droid";
#endif
#if WINDOWS_PHONE
var resourcePrefix = "Mapper.WinPhone";
#endif
var assembly = typeof(MainPage).GetTypeInfo().Assembly;
Stream stream = assembly.GetManifestResourceStream($"{resourcePrefix}.data.txt");
string text = "";
using (var reader = new System.IO.StreamReader(stream))
{
text = reader.ReadToEnd();
}
}
Reference Xamarin.Forms : Loading Files Embedded as Resources in Shared Projects
I've finally found the solution. It is not a good way to solve it but it works. My problem was giving the path of the text file wasn't working. The program couldn't read the text file. But using this code, the program itself finds the path of the text file and uses it.
private void LoadData()
{
var assembly = typeof(MapPage).GetTypeInfo().Assembly;
foreach (var res in assembly.GetManifestResourceNames())
{
if(res.Contains("data.txt"))
{
Stream stream = assembly.GetManifestResourceStream(res);
using (var reader = new StreamReader(stream))
{
string data = "";
while((data = reader.ReadLine()) != null)
{
var array = data.Split(' ');
dataArray.Add(new SensorModel()
{
left = Convert.ToInt32(array[0]),
right = Convert.ToInt32(array[1]),
front = Convert.ToInt32(array[2])
});
}
}
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With