我有一个文本文件,我有一些要点:
20,30
5,40
67,34
2,0
98,34
如何将此点添加到List?这是我的代码:
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);
}
}
答案 0 :(得分: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);
}
}
}
答案 1 :(得分: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);
}
}
答案 2 :(得分: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);
}
}