Wednesday, April 5, 2017

xna - How can I load a text file from Content?


I created a small Windows Phone game with XNA, but I have some trouble with loading a text file from Content. I added the text file to my Content project and marked the Build Action to "Content". The static text file should be loaded when the game starts, but I always get an exception in this line of the method:


if (File.Exists(filename)) 


An exception of type 'System.MethodAccessException' occurred in mscorlib.ni.dll but was not handled in user code



If there is a handler for this exception, the program may be safely continued.


What is wrong? How can I load a text file from Content?


private const string filename = "Level1.txt"; 

public void LoadfromContent()
{
if (File.Exists(filename))
{
using (StreamReader reader = new StreamReader(File.OpenRead(filename)))
{
strs = reader.ReadLine().Split(';');
game1.HowManyEnemies = int.Parse(strs[1]);
}
}

}

Answer



The content pipeline project is for content to be built with the content pipeline.


If your file will not be processed by the content pipeline, it needs to go in your main game project. Then follow the instructions from the link Byte56 gave you. Basically set "Content" and "Copy if newer".




The exception you are getting, MethodAccessException, is because that API isn't available on WP7. Use Title Storage instead. To open your file, you can use:


TitleContainer.OpenStream(filename);

See the information on MSDN about Reading Game Data from Title Storage and Adding Game Data Files to Title Storage.


No comments:

Post a Comment

Simple past, Present perfect Past perfect

Can you tell me which form of the following sentences is the correct one please? Imagine two friends discussing the gym... I was in a good s...