Importing file to array - c#

I want the user to be able to chose a text file written in a certain way (1 number per line) and then have the file converted into an array. I have bits and pieces of it working but I cant get it to all work at the same time. Any help would be appreciated.
private void Load_Button_Click(object sender, EventArgs e)
{
int counter = 0;
string line;
List<int> list = new List<int>();
string fileName = "";
//OpenFileDialog ofd = new OpenFileDialog();
//ofd.Filter = "TXT File|*.txt";
//ofd.Title = "Open File";
// if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
// {
File_Label.Text = "C:/Users/Neilan/Desktop/sample.txt";
//fileName = "#" + ofd.SafeFileName;
//MessageBox.Show(ofd.FileName);
System.IO.StreamReader file = new System.IO.StreamReader(#"C:\Users\Neilan\Desktop\sample.txt");
while ((line = file.ReadLine()) != null)
{
Unsorted_Box.Text += line + ", ";
//list.Add(int.Parse(fileName));
counter++;
}
dataArray = list.ToArray();
// }
}

You can do this.
var numberarray = File.ReadAllLines("stringpath").Select(int.Parse).ToArray();
Looking at your code, I guess you want to show these values in comma separated format to user. You can achieve this with following code snippet.
Unsorted_Box.Text = String.Join(",", numberarray.ToArray());
Hope this helps !

This problem can be solved by one line
var resultArray = Array.ConvertAll(System.IO.File.ReadAllLines("filename.type"), str => int.Parse(str));
Instead of "filename.type" you can put something like File_Label.Text

Related

How to store text file line by line into temporary list<string> after specific text

I would like to store line by line from the text file after read it. However, the text that store into the temporary list must be after the ": ".
Below is the example of content in my text file:
Name: Johny
Age: 18
Favourite: Basketball, Food
I would like to store Johny as list[0], 18 as list[1], and etc.
For the Favourite, it should be store separately such as Basketball as list[2] and Food as list[3] and etc. This is because I need to place it back to different textBox afterward.
Below is my example code:
private void storeDataList()
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.DefaultExt = ".txt";
ofd.Filter = "Text Document (*.txt) | *.txt";
string filename = ofd.FileName;
string line = "";
if (ofd.ShowDialog() == true)
{
StreamReader sr = new StreamReader(ofd.FileName);
while (line != null)
{
for (int i = 0; i < 10; i++)
{
List<string> elements = new List<string>();
string readText = File.ReadAllText(filename);
i = readText.LastIndexOf(": ");
elements.Add[i];
}
}
sr.Close();
detailsTextBox.Text = File.ReadAllText(filename);
}
}
Here's a one liner with LINQ that reads the file into lines, split the lines on : and takes what's after, then splits that on , for further granularity:
var output = File.ReadAllLines(filename).SelectMany(l => l.Split(':')[1].Split(',').Select(s => s.Trim());
Which outputs a list of: Johny, 18, Basketball, Food.
You can:
read it line by line
separate the fields and it's valued by splitting it with : delimiter
check the line every three-line
split the favorite value by comma delimiter ,
clean the value with trim to remove whitespaces
private void storeDataList()
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.DefaultExt = ".txt";
ofd.Filter = "Text Document (*.txt) | *.txt";
string filename = ofd.FileName;
string line = "";
if (ofd.ShowDialog() == true)
{
List<string> elements = new List<string>();
using (var reader = new StreamReader(ofd.FileName))
{
int rowNumber = 1;
//Dynamically stop the loop until the end of the stream
while (!reader.EndOfStream)
{
//Split to separate field name and values
var textLine = reader.ReadLine().Split(':');
//Since favorite fields are in multiples of three, we re-split the value by comma every three line
if (rowNumber % 3 == 0)
{
var favouriteArr = textLine[1].Split(',');
for (int i = 0; i < favouriteArr.Length; i++)
{
//trim to clean whitespace
elements.Add(favouriteArr[i].Trim());
}
}
else
{
elements.Add(textLine[1].Trim());
}
rowNumber++;
}
}
// # just a new delimiter to print the elements in a text box
detailsTextBox.Text = string.Join('#', elements);
}
}

How to link users file selection to a StringSplit

I'm trying to get the users chosen file to split into an array which is separated by , and /t.
The user can choose a file at the top of the code but how do I get their choice to split into an array lower down when they press the ValidateButton
The text file or ordered in this way
info,info,info,
info,info,info,
info,info,info,
If I can get them into an array then I can easily organises the data.
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.InitialDirectory = #"C:\"; // Start in C: drive
openFileDialog1.Title = "Browse Text Files";
openFileDialog1.RestoreDirectory = true;
openFileDialog1.DefaultExt = "txt"; // Extension of file is txt
openFileDialog1.Filter = "Text|*.txt||*.*"; //Only text files
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
FileNameBox.Text = openFileDialog1.FileName; // Chosen file name is displayed in text box
var fileStream = openFileDialog1.OpenFile();
using (StreamReader reader = new StreamReader(fileStream))
{
var fileContent = reader.ReadToEnd();
}
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
//This is the file path the user has chosen
}
public void ValidateButton_Click(object sender, EventArgs e)
{
//Call Multi line text box
//Call PROGRESS BAR_
int counter = 0;
string lines;
string Patient = lines;
string[] split = Patient.Split(new Char[] { ',', '\t' });
foreach (string s in split)
if (s.Trim() != "")
Console.WriteLine(s);
{
Console.WriteLine(lines);
counter++;
}
Console.WriteLine("There were {0} records.", counter);
Console.ReadKey();
}
List<string> temp = new List<string>();
string[] finalArray;
using (StreamReader reader = new StreamReader(fileStream))
{
// We read the file then we split it.
string lines = reader.ReadToEnd();
string[] splittedArray = lines.Split(',');
// We will check here if any of the strings is empty (or just whitespace).
foreach (string currentString in splittedArray)
{
if (currentString.Trim() != "")
{
// If the string is not empty then we add to our temporary list.
temp.Add(currentString);
}
}
// We have our splitted strings in temp List.
// If you need an array instead of List, you can use ToArray().
finalArray = temp.ToArray();
}

How to read numbers in a .txt file to an integer array?

I have a file that I need to save as an array. I am trying to convert a text file to an integer array using StreamReader. I just am unsure as to what to put in the for loop at the end of the code.
This is what I have so far:
//Global Variables
int[] Original;
//Load File
private void mnuLoad_Click_1(object sender, EventArgs e)
{
//code to load the numbers from a file
OpenFileDialog fd = new OpenFileDialog();
//open the file dialog and check if a file was selected
if (fd.ShowDialog() == DialogResult.OK)
{
//open file to read
StreamReader sr = new StreamReader(fd.OpenFile());
int Records = int.Parse(sr.ReadLine());
//Assign Array Sizes
Original = new int[Records];
int[] OriginalArray;
for (int i = 0; i < Records; i++)
{
//add code here
}
}
The .txt file is:
5
6
7
9
10
2
PS I am a beginner, so my coding skills are very basic!
UPDATE: I have previous experience using Line.Split and then mapping file to arrays but obviously that does not apply here, so what do I do now?
//as continued for above code
for (int i = 0; i < Records; i++)
{
int Line = int.Parse(sr.ReadLine());
OriginalArray = int.Parse(Line.Split(';')); //get error here
Original[i] = OriginalArray[0];
}
You should just be able to use similar code to what you had above it:
OriginalArray[i] = Convert.ToInt32(sr.ReadLine());
Every time the sr.ReadLine is called it increments the data pointer by 1 line, hence iterating through the array in the text file.
try this
OpenFileDialog fd = new OpenFileDialog();
if (fd.ShowDialog() == DialogResult.OK)
{
StreamReader reader = new StreamReader(fd.OpenFile());
var list = new List<int>();
while (!reader.EndOfStream)
{
var line = reader.ReadLine();
int value = 0;
if (!string.IsNullOrWhiteSpace(line) && int.TryParse(line, out value))
list.Add(value);
}
MessageBox.Show(list.Aggregate("", (x, y) => (string.IsNullOrWhiteSpace(x) ? "" : x + ", ") + y.ToString()));
}
You can read the entire file into a string array, then parse (checking the integrity of each one).
Something like:
int[] Original;
//Load File
private void mnuLoad_Click_1(object sender, EventArgs e)
{
//code to load the numbers from a file
var fd = new OpenFileDialog();
//open the file dialog and check if a file was selected
if (fd.ShowDialog() == DialogResult.OK)
{
var file = fd.FileName;
try
{
var ints = new List<int>();
var data = File.ReadAllLines(file);
foreach (var datum in data)
{
int value;
if (Int32.TryParse(datum, out value))
{
ints.Add(value);
}
}
Original = ints.ToArray();
}
catch (IOException)
{
// blah, error
}
}
}
Another way to do it if you'd like to read to the end of the file and you don't know how long it is with a while loop:
String line = String.Empty;
int i=0;
while((line = sr.ReadLine()) != null)
{
yourArray[i] = Convert.ToInt32(line);
i++;
//but if you only want to write to the file w/o any other operation
//you could just write w/o conversion or storing into an array
sw.WriteLine(line);
//or sw.Write(line + " "); if you'd like to have it in one row
}
//using linq & anonymous methods (via lambda)
string[] records = File.ReadAllLines(file);
int[] unsorted = Array.ConvertAll<string, int>(records, new Converter<string, int>(i => int.Parse(i)));

C# Adding 4923 Lines from a text file to DataGridView by skipping blank lines

I am new to C#. I have a huge text file consisting of 4923 lines of data that I wish to add to a DataGridView. The text file has a lot of spaces and blank lines in between sentences. I want that all the blank lines and spaces be skipped and load the contents to the DataGridView. Can someone give me a solution to achieve this? Can this be achieved without using DataTables and Datasource?
If my question is not clear please let me know. There may be mistakes in my code. Please help me rectify it
Thanks
This is my code
public void textload()
{
List<string> str = new List<string>();
String st = "";
//Path to write contents to text file
string filename = #"E:\Vivek\contentcopy\clientlist.txt";
Form.CheckForIllegalCrossThreadCalls = false;
OpenFileDialog ofd = new OpenFileDialog();
ofd.FileName = "";
ofd.Filter = "csv files|*.csv|txt files|*.txt|All Files|*.*";
ofd.ShowDialog();
st = ofd.FileName;
if (string.IsNullOrEmpty(ofd.FileName))
return;
string[] lines = File.ReadAllLines(st);
for (int i = 0; i < lines.Length; i++)
{
listBox1.Items.Add(lines[i]);
string[] s = lines[i].Split(' ');
MessageBox.Show(s.Length.ToString());
str.Add(lines[i]);
dataGridView1.Rows.Add();
if (s[i] == null && s[i] == " ")
{
continue;
}
dataGridView1.Rows[i].Cells[i].Value=s[i];
//dataGridView1.Rows[i].Cells[10].Value = s[10];
//dataGridView1.Rows[i].Cells[11].Value = s[11];
//dataGridView1.Rows[i].Cells[12].Value = s[12];
//dataGridView1.Rows[i].Cells[13].Value = s[13];
//dataGridView1.Rows[i].Cells[14].Value = s[14];
//dataGridView1.Rows[i].Cells[15].Value = s[15];
}
File.WriteAllLines(filename, str);
dataGridView1.ReadOnly = true;
}
One option is to filter out empty strings as soon as you've read it. This can be done with LINQ Where and passing condition that checks string for not being whitespace only. String.IsNullOrWhitepspace covers that (in addition it would check for null that will not happen in case of using ReadAllLines).
string[] lines = File.ReadAllLines(st)
.Where(s => !String.IsNullOrWhitespace(s))
.ToArray();

Read lines at different indexes

Here is some code i put together to search for numbers in a text file. It work's great for what i'm trying to do. right now it finds 7 locations and i need to read the lines at the 7 different indexes. what might be the best way to start this. Thanks, this is in C#.
private void button1_Click(object sender, EventArgs e)
{
richTextBox1.Text = "";
using (OpenFileDialog dlgOpen = new OpenFileDialog())
{
//long count = 0; string line;
//bool start = false;
//string line;
List<String> LinesFound = new List<string>();
// Available file extensions
dlgOpen.Filter = "All files(*.*)|*.*";
// Initial directory
dlgOpen.InitialDirectory = "C://bin";
// OpenFileDialog title
dlgOpen.Title = "Load";
// Show OpenFileDialog box
if (dlgOpen.ShowDialog() == DialogResult.OK)
textBox1.Text = dlgOpen.FileName;
{
string str = System.IO.File.ReadAllText(dlgOpen.FileName);
Regex reg = new Regex("333333");
Match sat = reg.Match(str);
while (sat.Success)
{
richTextBox1.Text += (sat.Index + " "); //shows index where 333333 is
sat = reg.Match(str, sat.Index + sat.Length);
{
{
}
}
}
}
}
}
You can use ReadAllLines instead of ReadAllText, and match each line one by one, use a int[] variable to store all your matching line index.
var lines = File.ReadAllLines(AppDomain.CurrentDomain.BaseDirectory + "/files/file.txt");
Regex reg = new Regex("333333");
string str;
for(int i =1; i<lines.Length;i++)
{
str = lines[i];
Match sat = reg.Match(str);
if (sat.Success)
{
richTextBox1.Text += (i + 1 +" "); //shows index where 333333 is
}
}

Categories

Resources