Main Site Documentation

Reading files through USB Host (title changed)


Hi I am trying to read contents of a text file from a flash memory plugged into a usb host module this is the way I am doing It :

 public void RemovableMedia_Insert(object sender, MediaEventArgs e)
            deviceInserted = true;
            display.SimpleGraphics.DisplayText("Storage \"" + e.Volume.Name + "\" is inserted.", Resources.GetFont(Resources.FontResources.NinaB), GT.Color.Red, 2, 10);
            if (e.Volume.IsFormatted)
                string[] files = Directory.GetFiles(e.Volume.RootDirectory);
                int j = 0;
                for (int i = 0; i < files.Length; i++)
                    string tmp = "";
                        tmp = files[i].ToString().Substring(files[i].Length - 15, 15);
                    catch { }

                    if (tmp == "PaymentList.txt")
                        j += 1;
                        display.SimpleGraphics.DisplayText(files[i].ToString().Substring(files[i].Length - 15, 15) + " was found", Resources.GetFont(Resources.FontResources.NinaB), GT.Color.Red, 2, (uint)((i * 20) + 30));
                        display.SimpleGraphics.DisplayText("Click the send button to send the file", Resources.GetFont(Resources.FontResources.NinaB), GT.Color.Red, 2, (uint)((i * 20) + 50));
                        FileStream fileStream = new FileStream(files[i], FileMode.Open);
                        data = new byte[fileStream.Length];
                        int k = fileStream.Read(data, 0, data.Length);
                            FileContentText = new string(Encoding.UTF8.GetChars(data, 0, data.Length));
                            //FileContentText = new string(GetChars(data, 0, data.Length));
                        catch (Exception ex)
                            string s = ex.Message;
                            if (ex.InnerException != null)
                                s = s + ex.InnerException.Message;
                            if (ex.InnerException != null)
                                s = s + ex.StackTrace;

                if (j == 0)
                    display.SimpleGraphics.DisplayText("There is no text file on your flash memory", Resources.GetFont(Resources.FontResources.NinaB), GT.Color.Red, 2, 30);
                    display.SimpleGraphics.DisplayText("with the name : PaymentList", Resources.GetFont(Resources.FontResources.NinaB), GT.Color.Red, 2, 50);
                    fileWasFound = false;
                    fileWasFound = true;
                Debug.Print("Storage is not formatted. Format on PC with FAT32/FAT16 first.");

at the following line :

I get the following exception :

An unhandled exception of type 'System.Exception' occurred in mscorlib.dll

any helps would be appreciated .


Not sure about this, but have you checked how many bytes rally have been read (return value of Read)?
Also check the content of data. May be UTF8.GetChars raises an error if the array does not contain valid UTF8 chars. Like when the last byte assumes that it’s an 2 byte character.
Is the file really UTF8 encoded?


@ karamafrooz - What system are you trying to read the flash memory from?


@ karamafrooz - Also, what is the value of data when you try to convert to char?


Show full code,
Are you sure you are Mounting the SD Card or USB Flash Drive…?



If the file contains character data, then I recommend using the StreamReader class.


But don’t use StreamReader.ReadLine().
If a new line falls on a multiple of 512 (internal buffer size) you get an exception.


@ Jay Jay -

I edited my question and added full code

I tried to mount flash memory but did not work so I used the RemovableMedia_Insert event handler


@ Mike -

I am trying to read a text file content , and Its all characters !

could you give me a snippet code with please ?


@ James -

I am trying to read a text file content

I saved the text file with different Encodings and tried to read It but It never worked !
Ofcourse I get bytes from :

but when trying to convert the byte to text the exception is throwen


I hope you do not mind but I changed the topic title to reflect the question.


1st you could use the following instead of going through the list of files:

var path = @ "SD\PaymentList.txt";
// alternatively (even better):
// var path = Path.Combine(e.Volume.RootDirectory, "PaymentList.txt");
if (File.Exists(path))
   using (var sr = new StreamReader(path))
      stringContent = sr.ReadToEnd(); // not sure about that, but similar

StreamReader automatically reads a UTF8 encoded file to string.

In your sample have a look the content of your data array after reading to it and before you decode it to a string.


I don’t have any sample code at my present location. This should help


In some forums this could backfire :hand:

You’re lucky that we are so nice :wink:

Btw. the community here can help as good as GHI, if it’s not OSHW lib Premium lib or directly hardware related (or FEZConfig, …) :wink:


I was more so referring to what kind of character data the text file contains. Is it ASCII or extended ASCII?


@ James -

I tried all different encodings (ascii , utf8 , … )but got the same result !


please post the content of the file or some of it’s content…
basically we want to know if it is Plan English or is it another language…



@ Jay Jay -

Hi Jay Jay

This is the content of my .txt file :


and this is the result I get when tryig to dead the file content using the code posted by Reinhard Ostermeier :


I should mention that I saved the .txt file with all different encodings (ASCII , UTF8 , Unicode , Big Endian Unicode ) and tied to read that but got the same result .


After all the restart solution worked again !!!

I formatted my flash memory and again created the PaymentList.txt file on that and I could read the file content !