How to link users file selection to a StringSplit - c#

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();
}

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);
}
}

Save Opened Text File to Original Location

I am creating an application that will allow me to open a .txt file and edit the values (weight=60, height =50, etc) in a DataGridView. My issue is that I am able to upload the .txt file using OpenFileDialog but am unable to write over and save it in it's previous location.
For clarification, here is my method to upload text files:
private void btnUpload_Click(object sender, EventArgs e)
{
Stream myStream;
openFileDialog1.FileName = string.Empty;
openFileDialog1.InitialDirectory = "C:\\";
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
var compareType = StringComparison.InvariantCultureIgnoreCase;
var fileName = Path.GetFileNameWithoutExtension(openFileDialog1.FileName);
var extension = Path.GetExtension(openFileDialog1.FileName);
if (extension.Equals(".txt", compareType))
{
try
{
using (myStream = openFileDialog1.OpenFile())
{
string file = Path.GetFileName(openFileDialog1.FileName);
string path = Path.GetDirectoryName(openFileDialog1.FileName);
StreamReader reader = new StreamReader(openFileDialog1.FileName);
string line;
while ((line = reader.ReadLine()) != null)
{
string[] words = line.Split('=');
paramList.Add(new Parameter(words[0], words[1]));
}
BindGrid();
}
}
And what I've tried to save the file:
public void WriteToTextFile(DataGridView dgvParam)
{
String file_name = Path.GetFileNameWithoutExtension(openFileDialog1.FileName);
using (StreamWriter objWriter = new StreamWriter(openFileDialog1.FileName))
{
for (Int32 row = 0; row < dgvParam.Rows.Count - 1; row++)
{
StringBuilder sb = new StringBuilder();
for (Int32 col = 0; col < dgvParam.Rows[row].Cells.Count; col++)
{
if (!String.IsNullOrEmpty(sb.ToString()))
sb.Append("="); //any delimiter you choose
sb.Append(dgvParam.Rows[row].Cells[col].Value.ToString().ToUpper());
}
objWriter.WriteLine(sb.ToString());
}
}
It says it is openFileDialog is currently in use and it cannot reach it! Any suggestions or recommendations would be really appreciated!
You need to dispose your reader variable.
You should get rid of the first using statement entirely and wrap that in a using statement instead.

Importing file to array

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

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)));

How do I check if one of the lines already exist in the text file?

string filename = "";
private void openToolStripMenuItem1_Click(object sender, EventArgs e)
{
OpenFileDialog theDialog = new OpenFileDialog();
theDialog.Title = "Open Text File";
theDialog.Filter = "TXT files|*.txt";
theDialog.InitialDirectory = #"C:\";
if (theDialog.ShowDialog() == DialogResult.OK)
{
lines = File.ReadAllLines(RecentFiles);
filename = theDialog.FileName;
for (int i = 0; i < lines.Length; i++)
{
recentfiles = new StreamWriter(RecentFiles, true);
recentfiles.WriteLine(theDialog.FileName);
recentfiles.Close();
items = File
.ReadLines(RecentFiles)
.Select(line => new ToolStripMenuItem()
{
Text = line
})
.ToArray();
recentFilesToolStripMenuItem.DropDownItems.AddRange(items);
}
TextFileContentToRichtextbox(filename);
}
}
I'm not sure if doing the for loop over the lines is right.
But what I want to do is when I open a new text file to check if it already exists in the RecentFiles(RecentFiles.txt) and if it does exist don't write it again.
Loop over lines and if after looping over all the lines and the variable filename does not exist then write it to the text file, and update the items.
Linq is perfect for this:
// if there are not any lines that equal the filename
if (!lines.Any(line => line.Equals(filename)))
{
// then write it into recent files text file
}
//// the below code will work only if a line has 1 fileName with extension or any text.
if (lines.Contains(filename, StringComparer.OrdinalIgnoreCase))
{
//// lines contains
}
else
{
////lines doesnot contain file name
}
Verify whether it full fill your requirement.

Categories

Resources