1

我有一个文本文件,其中有几点:

20,30
5,40
67,34
2,0
98,34

以及如何将此点添加到列表中?这是我制作的代码:

Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
dlg.DefaultExt = ".txt";
dlg.Filter = "Text document (.txt)|*.txt";

Nullable<bool> result = dlg.ShowDialog();

if (result == true)
{
    string filename = dlg.FileName;
    _mn.nazwa_pliku.Text = filename;

    int num = 0; //get a number of points/line in file

    for (int i = 0; i < num; i++) //for everyone line/point
    {

        int x = 0; //get X-value from file
        int y = 0; //get Y-value from file

        Klaster klaster = new Klaster();
        klaster.Punkty.Add(new Point(x, y));
        Klastry.Add(klaster);
    }       
}
4

3 回答 3

3
    void LoadCordinates()
    {
        StreamReader sr = new StreamReader("PATH OF FILE");

        Klaster klaster = new Klaster();
        while(sr.EndOfStream == false)
        {
           string temp = sr.ReadLine();
           if(temp.Contains(',') && temp.Split(',').Length == 2)
           {
               klaster.Punkty.Add(new Point(int.Parse(temp.Split(',')[0].Trim()), int.Parse(temp.Split(',')[0].Trim())));
               Klastry.Add(klaster);
           }
        }
    }
于 2012-10-22T18:13:45.607 回答
2

File.OpenText一种方法是逐行使用 和阅读:

// Open the stream and read it back. 
string s;
using (StreamReader sr = File.OpenText(filename)) 
{
    while ((s = sr.ReadLine()) != null) 
    {
        // parse the string and add the values to the list
        string[] parts = s.Split(new [] {','});
        if(parts.Length != 2)
        {
            // throw an exception
        }

        int x, y;

        if (!int.TryParse(parts[0],out x) ||
            !int.TryParse(parts[1],out y))
        {
            // throw an exception
        }

        Klaster klaster = new Klaster();
        klaster.Punkty.Add(new Point(x, y));
        Klastry.Add(klaster);
    }
}
于 2012-10-22T18:13:03.173 回答
1
Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
dlg.DefaultExt = ".txt";
dlg.Filter = "Text document (.txt)|*.txt";

Nullable<bool> result = dlg.ShowDialog();

if (result == true)
{
    string filename = dlg.FileName;
    _mn.nazwa_pliku.Text = filename;

    string[] lines = File.ReadAllLines(filename);

    foreach (var line in lines) //for everyone line/point
    {
        string[] elements = line.Split(',');
        int x = int.Parse(elements[0]); //get X-value from file
        int y = int.Parse(elements[1]); //get Y-value from file

        Klaster klaster = new Klaster();
        klaster.Punkty.Add(new Point(x, y));
        Klastry.Add(klaster);
    }       
}
于 2012-10-22T18:13:45.717 回答