Click here to Skip to main content
13,097,225 members (65,529 online)
Rate this:
Please Sign up or sign in to vote.
Hi guys, I am trying to read a text file that I have included with the project folder itself in a separate folder. I am trying to read this text file and then add each line to a list, each line as a separate item in the list, then I am looking to bind it to a listbox and each listbox item (each line previously) would be a hyperlink in the listbox. It's been very frustrating since the app just freezes every single time as soon as the code starts executing at runtime. What could be the problem?

public partial class Page2 : PhoneApplicationPage
       public Page2()
           // Will contain the names of malls added through a text file
           List<string> Mall_List = new List<string>();
           using(StreamReader reader = new StreamReader("/Mall_List/Mall_List.txt"))
                   while(reader.Peek() >= 0)
               Malllist.ItemsSource = Mall_List;

I have no idea at this point how to display the listbox items as hyperlinks so help is much appreciated, thanks!
Posted 1-Oct-12 5:16am

1 solution

Rate this: bad
Please Sign up or sign in to vote.

Solution 1

First of all, never do it in the constructor. Defer this part if initialization until the moment when the main event handling cycle of the application is already working, for example, when the main window is already shown. This way, the mechanism of catching of all of the exception in the main UI loop can be used.

If this file reading and processing procedure can also get some considerable time, do it in even more accurate way: do it in the separate thread.

This might be not the real reason of the hanging you observe. You need to execute your code under debugger to be sure.

[EDIT #1]

Also, there are no situations where a hard-coded path like your "/Mall_List/Mall_List.txt" could be useful, no matter if this is a relative or absolute path. Now your code depends on working directory, and this directory can be anywhere at all; it's defined by the user, how an application is started.

The file can be found relative to the executable directory, or "special folder" (System.Environment.GetFolderPath,[]), or calculated based on some configuration data — never hard-coded.

[EDIT #2: following up the discussion in the comments to this question]

I looks like you mix up working directory and executable directory. The working directory has nothing to do with the directory where your executable files are — it is defined be the user and can be anywhere. This is a parameter in a .LNK file; and if started directly, is still defined by the user. Most usually, this is the current working directory of some other program, like a file manager (Explorer or any other) at the moment when the user starts the application. So, it can be anywhere; and your program can change it. When you use a relative path, the actual path is found relative to the current working directory, which can be anything. This approach is often used in console applications, where a more experienced user directly controls the working directory and know where to provide and expect files.

The directory where your executable files are, in contrast, never changes unless you move those executable files and start the application again. Here is how to find it:
string location = System.Reflection.Assembly.GetEntryAssembly().Location;
string executableDirectory = System.IO.Path.GetDirectoryName(location);

Please pay attention, that this is a reliable method; there are other methods which can give you confusing results in some more special cases, but this will work the same way in all cases. I explain it in some more detail here:
How to find my programs directory [ (executable directory) ].

And I advised in the working directory and "special folder" here:
How to find my programs directory [ (current directory and "special folder") ].

I think now you should have comprehensive information on the directory issues.

Member 3733986 1-Oct-12 12:18pm
I took it out of the constructor and into the function that is executed when the button is pressed (there is a button on the main page which leads to page 2. Page 2 is supposed to show the list).

Still the same thing - freezes/hangs.
It was quite a good idea to try with the button click first; later you could change it.
If it hangs after the click -- please execute the handler's code under debugger, could you?
Member 3733986 1-Oct-12 14:06pm
Well I'll have to apologise because I'm a complete noob here lol. I've built a full game for Windows Phone 7 but never came across anything remotely close to file reading, so I haven't a clue about IsolatedStorage, even after reading about it in the links. The most I can understand is that direct access is impossible and IsolatedStorage may act as a temporary holder for whatever is to be loaded (to write or read).

And same thing with debugging pretty much. Never got the hang of it. If you can walk me through I can do it. Else if you'd like I can send the files over. The directory thing you wrote in the "edit" section of your original post left me confused because I'm used to the idea of packing everything needed within the directory of the entire program so the hard-coded file path is always going to refer to some file within that program's own directory, no matter which PC/user.
Oh, please, there is nothing to apologize about; in your search for some help, you act in a quite an appropriate way. Maybe the experience needed for a phone game is somewhat above your present experience, but you will gain it with time and learning.

Still, let's try to make one step at a time. First, why IsolatedStorage (pretty advanced concept, not often used), not just reading of a "regular" file?

And let me explain you mistake about the executable directory first. If you get it, it will be able to move a bit further...
Member 3733986 1-Oct-12 14:28pm
Thanks man.

I think you misread: I DID make a game for the phone, but since it was pure XNA/C# it had nothing to do with reading/writing (we didn't have enough time to take care of saving performance of the player). Thus I was apologising because I have made a game yet I'm stuck here with reading/writing lol.

It is a regular file. Before I learned about IsolatedStorage, I began with regular reading. Just a StreamReader doing the job. But whether IsolatedStorage or not, it hangs in the same way.

Yeah that would be a good start. Thanks.
I added [EDIT #2] on the directories to my answer, please see. I think now you have complete information on this part. Try to improve the file location part and then let's come back to the handing issue. You need to actively use the Debugger on the slightest concern about your run-time behavior.
Member 3733986 1-Oct-12 15:49pm
All right, I read through and tried to understand. I also downloaded a sample program that does this ( and I kept the program's directory open to see if the folder that the program creates itself appears or not. It doesn't. So from this, am I correct in understanding that the phone creates a random directory? Why exactly does it do that? I'm getting awfully confused because I am trying to read a file but I just can't access it. Furthermore, the sample program does not have this piece of code you provided with either:

string location = System.Reflection.Assembly.GetEntryAssembly().Location;
string executableDirectory = System.IO.Path.GetDirectoryName(location);

Do these two statements only get the path? How do I make sure that it is always saved in a particular location (should I create the file)? I also came across you saying, in one of the links^, that it's not a good idea to always use one specific area. Why exactly? I'm still a bit fuzzy but feel like I'm getting there (I have always been slow in understanding code with lines and stuff ... visual depiction is heaven for me).

I tried using these:

string location = System.Reflection.Assembly.GetEntryAssembly().Location;
string executableDirectory = System.IO.Path.GetDirectoryName(location);

but it underlines the "GetEntryAssembly()" method and says that System.Reflection.Assembly has no such definition.
What, you never added references so far? How do you think your assembly can access the assemblies from Basic Class Library (BCL) or Framework Class Library (FCL) of .NET?
In this case, you have to add the reference "System.Reflection". As this is BCL (which mostly indicates it is standardized with ECMA and ISO, with FCL it will be the same), this assembly is in GAC (Global Assembly Cache), so you add it from the tab ".NET" of the window "Add Reference".

You better read about all the terms I used above in Wikipedia, as well as ".NET", "CLI", "CLR", "CIL" or "IL"; it will be enough to get understanding.

Member 3733986 1-Oct-12 16:32pm
When I was checking the error, I immediately added a "using System.Reflection;" clause at the top, but it still didn't go.

I tried adding it as you said, but I cannot find it in the .NET tab.
You did not understand! Please read again. And please read on the topics "Assembly" and "namespace". Actually "using System.Reflection", does not add anything at all. It only changes the default naming. I mean, it you write "System.Reflection.Assembly myAssembly = //...", there is not difference at all, only "using System.Reflection" allows you to omit "System.Reflection." from "System.Reflection.Assembly". Nothing of it will work if you do not reference the assembly System.Reflection.

After all, search your "Solution Explorer" main tree to find "Add Reference"! (And then read the above comments again.) This is the most basic thing; without it, you are not doing any programming at all; need to learn it first and foremost. I already told you to read on the main topic.

Now, did you find it finally? If you did, now you can proceed. Everything you had before was just wrong. Reference the assembly. (Also, a bit later, read on "GAC" and "strong name", to understand what exactly the reference mean; and you can also look at the project file as the text, to see how a reference looks in the project.)

Member 3733986 1-Oct-12 16:47pm
Okay, I got confused between namespace and reference here, but I assure you, I right-clicked, clicked on "Add Reference" and I cannot find System.Reflection.
Sorry, I was confused myself. This is "mscorlib.dll", already referenced, in normal cases. Here is how to go about it: you look at the MSDN help, some class, and see the name of the assembly.

Now, I also failed to notice that you actually have the System.Assembly class, you don't have System.Assembly.GetEntryAssembly. This is because I forget that you are using the Windows Phone API, which is the highly reduced version of .NET. Sorry about all that trouble.

Let's find the appropriate API. Do you have System.Assembly.GetExecutingAssembly()? Or System.AppDomain.BaseDirectory? I mean you need to find the alternative method which is available in the Phone. My recipe may be not for your case. Or, do you have a Web references to MSDN help pages on System.Assembly? System.AppDomain? Application? The answer should be there...

Member 3733986 1-Oct-12 17:15pm
It isn't. I really don't know why.


I keep checking it to make sure the sleep isn't making me miss it. Thus far I haven't find it.
Right, it could be just because the target is WP7...
Member 3733986 1-Oct-12 17:18pm
Indeed. Just an app that reads a list of items in a text file and displays them in a listbox.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month

Advertise | Privacy |
Web03 | 2.8.170813.1 | Last Updated 1 Oct 2012
Copyright © CodeProject, 1999-2017
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100