Browse Source

Update CsvEditor scenario to use CsvHelper

tznind 2 years ago
parent
commit
2457f666d8
2 changed files with 27 additions and 17 deletions
  1. 24 17
      UICatalog/Scenarios/CsvEditor.cs
  2. 3 0
      UICatalog/UICatalog.csproj

+ 24 - 17
UICatalog/Scenarios/CsvEditor.cs

@@ -9,6 +9,7 @@ using System.IO;
 using System.Text;
 using NStack;
 using System.Text.RegularExpressions;
+using CsvHelper;
 
 namespace UICatalog.Scenarios {
 
@@ -394,34 +395,40 @@ namespace UICatalog.Scenarios {
 				Open(ofd.FilePath.ToString());
 			}
 		}
-		
-		private void Open(string filename)
+
+		private void Open (string filename)
 		{
-			
+
 			int lineNumber = 0;
 			currentFile = null;
 
+			using var reader = new CsvReader (File.OpenText (filename), CultureInfo.CurrentCulture);
+
 			try {
-				var dt = new DataTable();
-				var lines = File.ReadAllLines(filename);
-			
-				foreach(var h in lines[0].Split(',')){
-					dt.Columns.Add(h);
+				var dt = new DataTable ();
+				reader.Read ();
+
+				if (reader.ReadHeader ()) {
+					foreach (var h in reader.HeaderRecord) {
+						dt.Columns.Add (h);
+					}
 				}
-				
 
-				foreach(var line in lines.Skip(1)) {
+				while (reader.Read ()) {
 					lineNumber++;
-					dt.Rows.Add(line.Split(','));
+
+					var newRow = dt.Rows.Add ();
+					for (int i = 0; i < dt.Columns.Count; i++) {
+						newRow [i] = reader [i];
+					}
 				}
-				
+
 				tableView.Table = dt;
-				
-				// Only set the current filename if we succesfully loaded the entire file
+
+				// Only set the current filename if we successfully loaded the entire file
 				currentFile = filename;
-			}
-			catch(Exception ex) {
-				MessageBox.ErrorQuery("Open Failed",$"Error on line {lineNumber}{Environment.NewLine}{ex.Message}","Ok");
+			} catch (Exception ex) {
+				MessageBox.ErrorQuery ("Open Failed", $"Error on line {lineNumber}{Environment.NewLine}{ex.Message}", "Ok");
 			}
 		}
 		private void SetupScrollBar ()

+ 3 - 0
UICatalog/UICatalog.csproj

@@ -18,6 +18,9 @@
   <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
     <DefineConstants>TRACE;DEBUG_IDISPOSABLE</DefineConstants>
   </PropertyGroup>
+  <ItemGroup>
+    <PackageReference Include="CsvHelper" Version="30.0.0" />
+  </ItemGroup>
   <ItemGroup>
     <ProjectReference Include="..\Terminal.Gui\Terminal.Gui.csproj" />
   </ItemGroup>