简体   繁体   中英

How to assign values from text file to visual studio c#?

I am creating another solution from a website tutorial using visual studio 2015 c# (with some modifications to the code).

The xaml file:

<Window x:Class="WPFTestApplication.InsertPushpin"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:m="clr-namespace:Microsoft.Maps.MapControl.WPF;assembly=Microsoft.Maps.MapControl.WPF"
    Width="1024" Height="768">

    <Grid x:Name="LayoutRoot" Background="White">
        <m:Map CredentialsProvider="INSERT_YOUR_BING_MAPS_KEY">
        </m:Map>
    </Grid>
    </Window>

The xaml.cs file is as follows:

using System;
using System.Windows;
using System.Windows.Controls;
using System.Globalization;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using Microsoft.Maps.MapControl.WPF;
using Microsoft.Maps.MapControl.WPF.Design;

namespace WPFTestApplication
{
public partial class AddPushpinToMap : Window
{
    LocationConverter locConverter = new LocationConverter();

public AddPushpinToMap()
{
    InitializeComponent();
    Pushpin pin = new Pushpin();
    pin.Location = new Location(37.1481402218342, -119.644248783588);

    // Adds the pushpin to the map.
    myMap.Children.Add(pin);

  }
 }
}

I have a text file which contains float values in this format:

 1.234
 145.765
 1.267
 145.957

The first value is the latitude and the 2nd value is the longitude. This repeats for the 3rd and 4th, 5th and 6th etc.

I want to assign the 1st and 2nd values from the textfile to the line of code

     pin.Location = new Location(1st_value,2nd_value);

and then it will add a pushpin to the map.

But I'm a newbie and I'm not sure how to read from the text file and add the value to that line of code.

How can I assign the values from the text file to the line of code?

Thanks

You could use File.ReadLines method to read the file contents.

As a beginner you could start iterating over list using foreach .

var lines = File.ReadLines(filepath).ToList();
var locations = new List<Location>();
if(lines.Count() %2 !=0 ) throw new ArgumentException("invalid no.of vertices");

for(int i=0;i<lines.Count();i+=2)
{
    double lat = double.Parse(lines[i]);
    double lon = double.Parse(lines[i+1]);

    locations.Add(new Location(lat, lon));
}

If you are familiar with Linq you could do this with Linq as below.

var locations = File.ReadLines(filepath)
    .Select((line,i)=> new {line, index=i/2 })
    .GroupBy(x=>x.index)
    .Select(x=> new Location( double.Parse(x.First().line),double.Parse(x.Last().line)))
    .ToList();

This should give you something to start with,

        using (StreamReader reader = new StreamReader("*** your filepath ***"))
        {
            while (!reader.EndOfStream)
            {
                double lat = double.Parse(reader.ReadLine());
                double lon = double.Parse(reader.ReadLine());

                pin.Location = new Location(lat, lon);
            }
        }

This may help you: Use File.ReadAllLines to get all Lines(as Array) from the File. As per your input specifications the latitude will be in the First Line and the longitude will be at the second line, so that you can access them through their index. use double.TryParse() method to convert those values into double equivalent. Now consider the following code for this:

string textFilePath=@"local path to the file";
var Lines= System.IO.File.ReadAllLines(textFilePath);
double latitude,longitude;
double.TryParse(Lines[0],out latitude);
double.TryParse(Lines[1],out longitude); 
 pin.Location = new Location(latitude,longitude);

Once you read the file content, you could maintain collection of all the Latitude and Longitude information in List , and each list item would be pair of Latitude and Longitude values. Tuple should solve the purpose here.

    private void BuildGeoInfo()
    {
        string textFilePath = @"path to your text file";

        //Read all the contents of file as list of lines
        var fileLines = System.IO.File.ReadAllLines(textFilePath).ToList();

        //This list will hold the Latitude and Longitude information in pairs
        List<Tuple<double, double>> latLongInfoList = new List<Tuple<double, double>>();

        int index = 0;
        while (index < fileLines.Count)
        {
            var latLongInfo = new Tuple<double, double>(
                                  Convert.ToDouble(fileLines[index]),
                                  //++ to index to get value of next line 
                                  Convert.ToDouble(fileLines[index++]));

            latLongInfoList.Add(latLongInfo);

            index++; //++ to index to move to next line
        }
    }

You can then use the data in collection like this for example -

var latitude = latLongInfoList.First().Item1;
var longitude = latLongInfoList.First().Item2;
pin.Location = new Location(latitude,longitude);

Do check for the corner cases and handle them accordingly, like what if the lines are not in multiplier of two, type of each text line etc.

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