I am running the following C# code to read only the first 10 lines of a .txt file:
using MaterialDesignThemes.Wpf;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Data.SqlClient;
using System.Diagnostics;
using System.Data;
namespace TestEnvironment
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void BrowseButton_Click(object sender, RoutedEventArgs e)
{
// Create OpenFileDialog
Microsoft.Win32.OpenFileDialog openFileDlg = new Microsoft.Win32.OpenFileDialog();
// Launch OpenFileDialog by calling ShowDialog method
Nullable<bool> result = openFileDlg.ShowDialog();
// Get the selected file name and display in a TextBox.
// Load content of file in a TextBlock
if (result == true)
{
FileNameTextBox.Text = openFileDlg.FileName;
TextBlock1.Text = "Created on: " + System.IO.File.GetCreationTime(openFileDlg.FileName).ToString();
TextBlock1.Text += Environment.NewLine + Environment.NewLine + string.Join("\r\n", System.IO.File.ReadLines(openFileDlg.FileName).Take(10));
//System.IO.File.ReadLines(openFileDlg.FileName).Take(10).ToString()
Debug.WriteLine("Txt file contents!");
}
// Set filter for file extension and default file extension
openFileDlg.DefaultExt = ".txt";
openFileDlg.Filter = "Text files (*.txt)|*.txt|All files (*.*)|*.*";
Debug.WriteLine("Txt imported");
// Set initial directory
openFileDlg.InitialDirectory = @"C:\Documents\";
// Multiple selection with all file types
openFileDlg.Multiselect = true;
Debug.WriteLine("End!");
}
private void TabablzControl_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
}
}
}
Current output
But this what I want. I actually want to print the content in a table format, with column names and rows.
To do so I have searched for a similar question and found this. However, the answer posted there is using a fixed number of columns. But I want to make this method take a dynamic number of columns because my txt files don't have the same length of columns.
The code I run now:
using MaterialDesignThemes.Wpf;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Data.SqlClient;
using System.Diagnostics;
using System.Data;
namespace TestEnvironment
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
public DataTable ConvertToDataTable(string filePath, int numberOfColumns)
{
DataTable tbl = new DataTable();
for (int col = 0; col < numberOfColumns; col++)
tbl.Columns.Add(new DataColumn("Column" + (col + 1).ToString()));
string[] lines = System.IO.File.ReadAllLines(filePath);
var lines1 = lines.Take(10);
Debug.WriteLine(lines1);
foreach (string line in lines1)
{
var cols = line.Split('\t');
DataRow dr = tbl.NewRow();
for (int cIndex = 0; cIndex < line.Length; cIndex++)
{
dr[cIndex] = cols[cIndex];
}
tbl.Rows.Add(dr);
}
return tbl;
}
private void BrowseButton_Click(object sender, RoutedEventArgs e)
{
// Create OpenFileDialog
Microsoft.Win32.OpenFileDialog openFileDlg = new Microsoft.Win32.OpenFileDialog();
// Launch OpenFileDialog by calling ShowDialog method
Nullable<bool> result = openFileDlg.ShowDialog();
// Get the selected file name and display in a TextBox.
// Load content of file in a TextBlock
if (result == true)
{
FileNameTextBox.Text = openFileDlg.FileName;
TextBlock1.Text = "Created on: " + System.IO.File.GetCreationTime(openFileDlg.FileName).ToString();
var travelTime = ConvertToDataTable(filePath: openFileDlg.FileName, numberOfColumns: 1);
TextBlock1.Text += Environment.NewLine + Environment.NewLine + travelTime;
//TextBlock1.Text += Environment.NewLine + Environment.NewLine + string.Join("\r\n", System.IO.File.ReadLines(openFileDlg.FileName).Take(10));
//System.IO.File.ReadLines(openFileDlg.FileName).Take(10).ToString()
Debug.WriteLine("Txt file contents!");
}
// Set filter for file extension and default file extension
openFileDlg.DefaultExt = ".txt";
openFileDlg.Filter = "Text files (*.txt)|*.txt|All files (*.*)|*.*";
Debug.WriteLine("Txt imported");
// Set initial directory
openFileDlg.InitialDirectory = @"C:\Documents\";
// Multiple selection with all file types
openFileDlg.Multiselect = true;
Debug.WriteLine("End!");
}
private void TabablzControl_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
}
}
}
I get the following error:
Thank you in advance for any comments and help. Happy to provide more info is something was not clear.
A dummy .txt file I created my self can be found here
[UPDATE] based on the comments
After running this: (credits to: gkulshrestha)
public DataTable ConvertToDataTable(string filePath)
{
DataTable tbl = new DataTable();
string[] lines = System.IO.File.ReadAllLines(filePath);
var lines1 = lines.Take(10);
for (int col = 0; col < lines1.First().Split('\t').Length; col++)
tbl.Columns.Add(new DataColumn("Column" + (col + 1).ToString()));
foreach (string line in lines1)
{
var cols = line.Split('\t');
DataRow dr = tbl.NewRow();
for (int cIndex = 0; cIndex < cols.Length; cIndex++)
{
dr[cIndex] = cols[cIndex];
}
tbl.Rows.Add(dr);
}
return tbl;
}
if (result == true)
{
FileNameTextBox.Text = openFileDlg.FileName;
TextBlock1.Text = "Created on: " + System.IO.File.GetCreationTime(openFileDlg.FileName).ToString();
TextBlock1.Text += Environment.NewLine + Environment.NewLine + ConvertToDataTable(filePath: openFileDlg.FileName);
//TextBlock1.Text += Environment.NewLine + Environment.NewLine + string.Join("\r\n", System.IO.File.ReadLines(openFileDlg.FileName).Take(10));
//System.IO.File.ReadLines(openFileDlg.FileName).Take(10).ToString()
Debug.WriteLine("Txt file contents!");
}
I get nothing in return but only the created on Date which is the first Text of my TextBox
[UPDATE 2: Need for encoding the Row.Add content to UTF-8]
I am trying to encode the content of the Row.Add() into UTF-8. Now its ANSI. Searching online I came across online articles.
So my DataGrid table method looks like:
public DataTable ConvertToDataTable(string filePath)
{
DataTable tbl = new DataTable();
// Take the first 10 lines
var lines = File.ReadLines(filePath).Take(10);
// Split each line and create an integer sequence where each value
// is the number of the splitted elements
// then get the max value present in this sequence
var max = lines.Select(x => x.Split('\t').Length).Max();
// First line contains headers
string[] headers = lines.First().Split('\t');
// Now create the table with the max number of columns present
for (int col = 0; col < max; col++)
tbl.Columns.Add(new DataColumn(headers[col]));
//Use the Rows.Add method that accepts an object array
foreach (string line in lines.Skip(1))
{
//tbl.Rows.Add(line.Split('\t'));
var utf8 = Encoding.UTF8;
byte[] utfBytes = utf8.GetBytes(tbl.Rows.Add(line.Split('\t')));
var myReturnedString = utf8.GetString(utfBytes);
tbl.Rows.Add(myReturnedString);
}
foreach (DataRow dr in tbl.Rows)
{
Debug.WriteLine(dr["Nationality"]);
string s = dr["Nationality"].ToString();
byte[] bytes = Encoding.Default.GetBytes(s);
dr["Nationality"] = Encoding.UTF8.GetString(bytes);
Debug.WriteLine(dr["Nationality"]);
}
return tbl;
}
But inside the Row.Add() method I get an error:
Cannot convert from 'System.Data.DataRow' to 'char[]'