public void AddLabel(int offset, Label label, bool overwrite) { // adding null label removes it if (label == null) { if (Labels.ContainsKey(offset)) { Labels.Remove(offset); } return; } if (overwrite) { if (Labels.ContainsKey(offset)) { Labels.Remove(offset); } } if (!Labels.ContainsKey(offset)) { label.CleanUp(); Labels.Add(offset, label); } }
private void ImportLabelsFromCsv(bool replaceAll) { OpenFileDialog open = new OpenFileDialog(); open.Filter = "Comma Separated Value Files|*.csv|Text Files|*.txt|All Files|*.*"; var result = open.ShowDialog(); if (result != DialogResult.OK || open.FileName == "") { return; } var errLine = 0; try { var newValues = new Dictionary <int, Label>(); var lines = Util.ReadLines(open.FileName).ToArray(); var validLabelChars = new Regex(@"^([a-zA-Z0-9_\-]*)$"); // NOTE: this is kind of a risky way to parse CSV files, won't deal with weirdness in the comments // section. for (var i = 0; i < lines.Length; i++) { var label = new Label(); errLine = i + 1; SplitOnFirstComma(lines[i], out var labelAddress, out var remainder); SplitOnFirstComma(remainder, out label.Name, out label.Comment); label.CleanUp(); label.Name = label.Name.Trim(); if (!validLabelChars.Match(label.Name).Success) { throw new InvalidDataException("invalid label name: " + label.Name); } newValues.Add(int.Parse(labelAddress, NumberStyles.HexNumber, null), label); } // everything read OK, modify the existing list now. point of no return if (replaceAll) { Project.Data.DeleteAllLabels(); } ClearAndInvalidateDataGrid(); // this will call AddRow() to add items back to the UI datagrid. foreach (var pair in newValues) { Project.Data.AddLabel(pair.Key, pair.Value, true); } } catch (Exception ex) { MessageBox.Show( "An error occurred while parsing the file.\n" + ex.Message + (errLine > 0 ? $" (Check line {errLine}.)" : ""), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } }