[mono-android] Reading from a file

Jonathan Pryor jonp at xamarin.com
Wed Jan 11 21:54:26 UTC 2012


On Dec 22, 2011, at 4:49 PM, John Croft wrote:
> I have the following code:

Runtime behavior will depend upon the contents of the QUICKEDIT_FILENAME file, which you don't provide. That makes it rather hard to reproduce. :-)

So, my equivalent code works:

	void TestStreamInvokers (TextView textview)
	{
		bool success = true;
		var test_string = "hello";

		Stream osa = OpenFileOutput ("test.txt", FileCreationMode.Private);
		var write_bytes = System.Text.Encoding.ASCII.GetBytes (test_string);

		osa.Write (write_bytes, 0, write_bytes.Length);
		osa.Close ();

		Stream isa = OpenFileInput ("test.txt");
		var content = new byte[1024];
		if (isa.Read(content,0,content.Length) > 0)
		{
			UTF8Encoding enc = new UTF8Encoding();
			if (enc.GetChars(content).Length>0)
				Console.WriteLine (enc.GetChars(content),0,(enc.GetChars(content)).Length-1);
		}
		isa.Close ();
	}

That said, I find your code to be rather...odd:

> void OpenFile()
>        {
>            byte[] content = new byte[1024];
>            try
>            {
>                Stream fis = OpenFileInput(QUICKEDIT_FILENAME);
>                if (fis.Read(content,0,content.Length) > 0)

Stream.Read() does not "null terminate" the buffer. You shouldn't discard the return value, as that tells how many bytes were actually written into `content`. If you reused the buffer (which you don't here, but if you did), you may have "garbage data" left from a previous loop invocation that would then be appended to your later strings.

> Any thoughts would be appreciated.

It's possible that QUICKEDIT_FILENAME contains data that UTF8Encoding doesn't like, such as an invalid byte sequence or a byte sequence which is aborted mid-sequence. Without knowing the contents, it's hard to say.

 - Jon



More information about the Monodroid mailing list