How to read from a text file?

I need to use a dictionary for my program and I've looked through the tutorial at:
http://developer.xamarin.com/Guides/Android/Application_Fundamentals/Resources_in_Android/part_6_-_using_android_assets/

I've written identical code and the file opener doesn't work. I've put a file called Dictionary.txt in the android project's Assets folder, and set its build action to AndroidAsset. The exception that gets caught basically says null reference exception at the Assets.Open line. So what am I doing wrong?
using System;
using System.IO;
using System.Collections;
using Android.App;
using Android.Content.Res;
namespace DrawingTest
{
public class Dictionary : Activity
{
//the arraylist that all the words will be loaded into
private ArrayList dictionary;

    /// <summary>
    /// Uses a stream to get all the words out of the dictionary text file
    /// and load them into memory, so that they can be searched
    /// </summary>
    /// <returns>True if successful, false if the dictionary couldn't be opened</returns>
    public bool Initialize()
    {
        dictionary = new ArrayList();
        try
        {
            using ( StreamReader sr = new StreamReader( Assets.Open( "Dictionary.txt" ) ) )
            {
                String line;
                while ( ( line = sr.ReadLine() ) != null )
                {
                    dictionary.Add( line );
                }
            }
        }
        catch ( Exception e )
        {
            return false;
        }
        return true;
    }

    /// <summary>
    /// Use binary search to detect whether or not
    /// the input string exists in the dictionary
    /// </summary>
    /// <param name="find">The string to compare</param>
    /// <returns>Whether or not the input string is a real word</returns>
    public bool search( string find )
    {
        find = find.ToLower();
        if ( dictionary.BinarySearch( find ) >= 0 )
        {
            return true;
        }
        return false;
    }
}
    }

Answers

  • fbs419fbs419 ✭✭ USMember ✭✭

    Could it be a case problem? What if you name the file dictionary.txt instead of Dictionary.txt?

  • Corey.0188Corey.0188 USMember

    I tried changing a bunch of things to no avail, what I have found out is that for some reason opening the stream in the OnCreate method of the MainActivity class works even though it fails in multiple other places. This could be partly due to the presence of the Bundle object even though it isn't directly referenced, but this framework is still too poorly documented to make that call.

Sign In or Register to comment.