简体   繁体   中英

How to supply C# application with data from a text file?

I have a text file data.txt which has this data on it:

5 5
1 2 N
LMLMLMLMM
3 3 E
MMRMMRMRRM

My application can read the data from the file:

System.IO.StreamReader = dataFile = new System.IO.StreamReader("C\\data.txt");
string myData = dataFile.ReadToEnd();               

And I can split the string:

Array splitString = myData.Split(' ');

Now I want to use the splitted string as values on my program, like this:

     Grid viewGrid = new Grid(Coordinates(5,5));
     viewGrid.AddToCollection(new Rov(1,2,'N',"LMLMLMLMM"));
     viewGrid.AddToCollection(new Rov(3,3,'E',"MMRMMRMRRM"));

I would go with something like

List<string> Data = System.IO.File.ReadAllLines(filename);

string[] coordLine = Data[0].Split(' ');
Grid viewGrid = new Grid(Coordinates(int.Parse(coordLine [0]), int.Parse(coordLine [1]));

for (int i = 1; i < Data.Count / 2; i++)
{
    string[] line1 = Data[2 * i - 1].Split(' ');
    string line2 = Data[2 * i];

    viewGrid.AddToCollection(new Rov(Int32.Parse(line1[0]), Int32.Parse(line1[1]), line1[2], line2));
}

This works or any odd number of lines (one line for coordinates and pairs for your objects).

In case your text file is always in the same format you can easily use the string array and hardcode the order of the appearing elements. To convert the strings to numbers you can use Int32.Parse('1') .

Grid viewGrid = new Grid(Coordinates(Int32.Parse(splitString[0]), Int32.Parse(splitString[1])));
viewGrid.AddToCollection(new Rov(Int32.Parse(splitString[2]), Int32.Parse(splitString[3]), splitString[4], splitString[5]));
viewGrid.AddToCollection(new Rov(Int32.Parse(splitString[6]), Int32.Parse(splitString[7]), splitString[8], splitString[9]));
Grid viewGrid = new Grid(Coordinates(int.Parse(splitString[0]), int.Parse(splitString[1])));
viewGrid.AddToCollection(new Row(int.Parse(splitString[2]), int.Parse(splitString[3]),splitString[4],splitString[5]));
viewGrid.AddToCollection(new Row(int.Parse(splitString[6]), int.Parse(splitString[7]),splitString[8],splitString[9]));
Array splitString = myData.Split('\n');
        Array cords = splitString[0].ToString().Split(' ');
        int cordX = Convert.ToInt32(cords[0]);
        int cordY = Convert.ToInt32(cords[1]);

        Grid viewGrid = new Grid(Coordinates(cordX, cordY));

        for (int i = 1; i < splitString.Length; i++)
        {
            Array nxtSplit = splitString[i].ToString().Split(' ');
            int x = int.Parse(nxtSplit[0]);
            int y = int.Parse(nxtSplit[1]);
            char c = Convert.ToChar(nxtSplit[2]);
            i++;
            string s = splitString[i].ToString();
            viewGrid.AddToCollection(new Rov(x, y, c, s));
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM