Nirish Alakhramsing
Nirish Alakhramsing

Reputation: 11

Reading a text file from Unity3d

I have a error in a script which reads from a text file outside the program. The error is

FormatException: Input string was not in the correct format

Its obvious whats wrong, but I just don't understand why it cant read it properly. My code:

using (FileStream fs = new FileStream(@"D:\Program Files (x86)\Steam\SteamApps\common\blabla...to my file.txt))
        {
            byte[] b = new byte[1024];
            UTF8Encoding temp = new UTF8Encoding(true);

            while (fs.Read(b, 0, b.Length) > 0)
            {
                //Debug.Log(temp.GetString(b));
                var converToInt = int.Parse(temp.GetString(b));
                externalAmount = converToInt;

            }
            fs.Close();
        }

The text file has 4 lines of values. Each line represent a object in a game. All I am trying to do is read these values. Unfortunately I get the error which I can't explain. So how can I read new lines without getting the error?

the text file looks like this

12
5
6
0

4 lines no more, all values on a seperate line.

Upvotes: 1

Views: 1135

Answers (2)

ashbygeek
ashbygeek

Reputation: 761

A couple problems:

Problem 1

fs.Read(b, 0, b.Length) may read one byte, or all of them. The normal way to read a text file like this is to use StreamReader instead of FileStream. The Streamreader has a convenience constructor for opening a file that works the same way, but it can read line by line and is much more convenient. Here's the documentation and an excellent example: https://msdn.microsoft.com/en-us/library/f2ke0fzy(v=vs.110).aspx

If you insist on reading directly from a filestream, you will either need to

  • Parse your string outside the loop so you can be certain you've read the whole file into your byte buffer (b), or

  • Parse the new content byte by byte until you find a particular separator (for example a space or a newline) and then parse everything in your buffer and reset the buffer.

Problem 2

Most likely your buffer already contains everything in the file. Your file is so small that the filestream object is probably reading the whole thing in a single shot, even though that's not gauranteed.

Since your string buffer contains ALL the characters in the file you are effectively trying to parse "12\n5\n6\n0" as an integer and the parser is choking on the newline characters. Since newlines are non-numeric, it has no idea how to interpret them.

Upvotes: 1

Fredrik
Fredrik

Reputation: 5108

There's no closing " on your new Filestream(" ...); but I'm gonna assume that's an issue when copy pasting your code to Stackoverflow.

The error you're getting is likely because you're trying to parse spaces to int, which wont work; the input string (" " in this case) was not in the correct format (int).

Split your lines on spaces (Split.(' ')) and parse every item in the created array.

Upvotes: 2

Related Questions