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]);
}
}
}
Firstly I would split the text based on NewLine, as to get the individual lines, and then based on the field seperator.
something like
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