Reputation: 425
I have a .csv file I'd like to modify. Here is the format of the file:
Id, UTMGridEast, UTMGridNorth, LocDate, LocTime, Species
What I have done already is create an arraylist of all these values, but what I would like to do is create an arraylist of all the values and each line in the dataset is another array. This is because I need to edit the fields UTMGridEast
and UTMGridNorth
and then reinsert them into the arraylist.
My GUI consists of just two buttons, here is my code so far:
public partial class MainWindow : Window
{
private string _filename;
private string[] _splitValues;
public MainWindow()
{
InitializeComponent();
}
private void btnLoad_Click(object sender, RoutedEventArgs e)
{
// Configure open file dialog box
Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
dlg.FileName = "Dataset"; // Default file name
dlg.DefaultExt = ".txt"; // Default file extension
dlg.Filter = "Commar Seperated Values (.csv)|*.csv" ; // Filter files by extension
// Show open file dialog box
Nullable<bool> result = dlg.ShowDialog();
// Process open file dialog box results
if (result == true)
{
// Open document
_filename = dlg.FileName;
txtFilePath.Text = _filename;
}
}
private void btnConvert_Click(object sender, RoutedEventArgs e)
{
ConvertToLatLong();
}
private void ConvertToLatLong()
{
string textFile = System.IO.File.ReadAllText(_filename);
foreach (var value in textFile)
{
_splitValues = textFile.Split(',');
Console.WriteLine("Split values: " + _splitValues[value]);
}
}
}
Upvotes: 2
Views: 532
Reputation: 6850
I'm not sure what type _splitValues
is, but assuming a List<String[]>
will work:
private void ConvertToLatLong()
{
var lines = from line in System.IO.File.ReadLines("foo")
let splitLine = line.Split(',')
select splitLine.Select(x => x.Trim()).ToArray();
_splitValues = lines.ToList();
}
Upvotes: 1
Reputation: 166606
Firstly I would split the text based on NewLine, as to get the individual lines, and then based on the field seperator.
something like
List<string> lines = new List<string>(textFile.Split(new[] { Environment.NewLine }, StringSplitOptions.None));
for (int iLine = 0; iLine < lines.Count; iLine++)
{
List<string> values = new List<string>(lines[iLine].Split(new[] {","}, StringSplitOptions.None));
for (int iValue = 0; iValue < values.Count; iValue++)
Console.WriteLine(String.Format("Line {0} Value {1} : {2}", iLine, iValue, values[iValue]));
}
But as I have always said, rolling your own CSV parser is very difficult.
Have a look at Comma-separated values
Specifically at the section Basic rules and examples
What I would recomend is C# Tutorial - Using The Built In OLEDB CSV Parser
Upvotes: 1