c# store textbox(file content) lines into array - c#

Hey I am currently stuck. I have the following code that takes a line from a file, based on specific string and returns it, then it can be edited, and applied back to a textbox that contains the file content into the line that the string was initially taken from.
private void citationChange()
{
List<string> matchedList = new List<string>();
string[] linesArr = File.ReadAllLines(fileName);
//find matches
for (int a = 0; a < linesArr.Length; a++)
{
string s = linesArr[a];
if (s.Contains(citation))
{
matchedList.Add(linesArr[a]); //matched
lineBeingEdited = a;
break; //breaks the loop when a match is found
}
}
//output
foreach (string s in matchedList)
{
string citationLine = s;
string[] lineData = citationLine.Split(',');
editModuleComboBox.Text = lineData[1];
selectedModuleLabel.Text = lineData[2];
moduleTitleTextBox.Text = lineData[3];
creditsTextBox.Text = lineData[4];
semesterTextBox.Text = lineData[5];
examWeightingTextBox.Text = lineData[6];
examMarkTextBox.Text = lineData[7];
testWeightingTextBox.Text = lineData[8];
testMarkTextBox.Text = lineData[9];
courseworkWeightingTextBox.Text = lineData[10];
courseworkMarkTexbox.Text = lineData[11];
}
}
How can I recreate/change this code but for it to read a textbox instead of a file?
Thanks

Change this:
string[] linesArr = File.ReadAllLines(fileName);
to:
string[] linesArr = theTextBox.Text.Split(new string[] { Environment.NewLine }, StringSplitOptions.None);

When reading your file File.ReadAllLines basically splits the entire text by \r\n. So you could do this with your text from the textbox:
exchange this line:
string[] linesArr = File.ReadAllLines(fileName);
to this:
string[] linesArr = YourTextBox.Text.Split(new string[] { Environment.NewLine }, StringSplitOptions.None);
or this:
string[] linesArr = YourTextBox.Text.Split(new char[] {'\r', '\n'});

Related

How to get data from text resource file and put in combobox

I have many files of data in txt files like this short example
123456
754124
956412
789654
They can have tens of lines in each file. Each file populates a separate combobox. From a static file in a folder I can make it work
string[] fname = {"fridge", "washer", "freezer", "dishwasher"};
for (int i = 0; i < fname.Length; i++)
{
string[] lineOfContents = File.ReadAllLines(#"d:\\temp\\" + fname[i] + ".txt");
ComboBox cmbobox = (ComboBox)this.Controls["cmbobx_" + fname[i]];
foreach (var line in lineOfContents)
{
string[] data = line.Split(new[] {Environment.NewLine}, StringSplitOptions.None);
cmbobox.Items.Add(data[0]);
}
cmbobox.SelectedIndex = 0;
}
but I need to do this when I read the data from embedded resources. I pulled the text files into the project.properties.resources so I have them inside the exe. I understand I will need to stream it out from resources but then I get lost in knowing how to convert the stream with all its newlines etc and format it to add it to the combobox.
I tried many things and the closest I think I have got is as follows although it tells me I have hold of nothing (NULL).
string[] fname = {"fridge", "washer", "freezer", "dishwasher"};
var assembly = Assembly.GetExecutingAssembly();
for (int i = 0; i < fname.Length; i++)
{
string lineOfContents;
string name = fname[i] + ".txt";
using (Stream resourceStream = assembly.GetManifestResourceStream(name))
{
if (resourceStream != null)
{
using (StreamReader reader = new StreamReader(resourceStream))
{
lineOfContents = reader.ReadToEnd();
}
}
}
ComboBox cmbobox = (ComboBox)this.Controls["cmbobx_" + fname[i]];
cmbobox.SelectedIndex = 0;
}
Any help in getting the stream into the combo box would be much appreciated.
Thanks for the link below, I did not get that when I searched so thanks and it helped. The working code before I tidy it up is:
string[] fname = {"fridge", "washer", "freezer", "dishwasher"};
for (int i = 0; i < fname.Length; i++)
{
string resource_data = Properties.Resources.ResourceManager.GetString(fname[i]);
string[] lineOfContents = resource_data.Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
ComboBox cmbobox = (ComboBox)this.Controls["cmbobx_" + fname[i]];
foreach (var line in lineOfContents)
{
string[] data = line.Split(new[] {Environment.NewLine}, StringSplitOptions.None);
cmbobox.Items.Add(data[0]);
}
cmbobox.SelectedIndex = 0;
}
Thanks for the links, I did not get that when I searched so thanks and it helped. The working code before I tidy it up is:
string[] fname = {"fridge", "washer", "freezer", "dishwasher"};
for (int i = 0; i < fname.Length; i++)
{
string resource_data = Properties.Resources.ResourceManager.GetString(fname[i]);
string[] lineOfContents = resource_data.Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
ComboBox cmbobox = (ComboBox)this.Controls["cmbobx_" + fname[i]];
foreach (var line in lineOfContents)
{
string[] data = line.Split(new[] {Environment.NewLine}, StringSplitOptions.None);
cmbobox.Items.Add(data[0]);
}
cmbobox.SelectedIndex = 0;
}

Data separated by column in C# from a text file

File txt
I have this file in text and need to organize ordered in table.
OBS: need to be console app c #
I did it only:
StreamReader sr = new StreamReader(#"filepatch.txt");
string ler = sr.ReadLine();
string linha = ";";
int cont = 0;
while((linha = sr.ReadLine())!= null)
{
string col = linha.Split(';')[2];
cont++;
Console.WriteLine("{0} : {1}", cont, linha);
}
Try this to get the file text:
var lines = System.IO.File.ReadAllLines(#"filepatch.txt");
Then you can use the returned string[] to carry out the rest of your logic.
foreach(var line in lines)
{
string[] cols = line.Split(';');
// Your logic here.
}
Cheers!

LINQ unable to OrderBy date in specific column?

I have a CSV file which goes like this:
1,01/01/2001,a
2,19/09/2013,as
3,12/05/2016,asd
4,13/05/2016,asdf
5,12/12/2012,asdfg
6,05/02/2006,asdfgh
7,06/03/2011,asdfghj
I want to sort and display the dates in chronological order but I can't seem to get my code to sort it out. However, my code is able to display the dates according to the format in the CSV file.
If the CSV file is like this:
01/01/2001
19/09/2013
12/05/2016
13/05/2016
12/12/2012
05/02/2006
06/03/2011
Then, it works just fine.
The following is my code:
string parts = new StreamReader(#"C:\input.txt").ReadToEnd();
string[] file = parts.Split(new string[] { Environment.NewLine }, StringSplitOptions.None);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < file.Length; i++)
{
string[] data = file[i].Split(new string[] { "," }, StringSplitOptions.None);
string[] dates = new string[] { data[1].ToString() };
//var date = dates.OrderBy(x => DateTime.Parse(x)).ToList();
var date = dates.OrderBy(x => DateTime.ParseExact(x, "dd/MM/yyyy", null));
foreach (string s in date)
{
sb.AppendLine(s + "<br />");
Label1.Text = sb.ToString();
}
}
I have tested this code using both DateTime.Parse and DateTime.ParseExact on the CSV file, but they didn't work.
I'm really new to LINQ query and this is my first time using it. I would really appreciate it if there is an explanation provided on what's wrong with my code.
You are sorting an array (dates) that always contains one date (because you create it each time from a single line in a loop). Then you add this line to the label's text.
You have to create a collection that contains all the dates, before you sort it.
string parts = new StringReader(#"C:\input.txt").ReadToEnd();
string[] lines = parts.Split(new string[] {Environment.NewLine}, StringSplitOptions.None);
StringBuilder sb = new StringBuilder();
List<string> dates = new List<string>();
for (int i = 0; i < lines.Length; i++)
{
string[] data = lines[i].Split(new string[] { "," }, StringSplitOptions.None);
dates.Add(data[1]);
}
var datesSorted = dates.OrderBy(x => DateTime.ParseExact(x, "dd/MM/yyyy", null));
foreach (string s in datesSorted)
{
sb.AppendLine(s + "<br />");
}
Label1.Text = sb.ToString();
It may required to select the values in Date format first then order it
Try
var date = dates.Select(x => DateTime.ParseExact(x, "dd/MM/yyyy", null)).OrderBy(t => t).ToList();
foreach (DateTime s in date)
{
sb.AppendLine(s.ToString("dd/MM/yyyy") + "<br />");
}
Label1.Text = sb.ToString();
Need to move the Label1 Text assigning after foreach
Please first put your dates into a Collection, for example a List or Array, and then sort the Collection. Default sort order is ascending
List<string> unsortedDates = new List<string>();
string parts = new StreamReader(#"C:\input.txt").ReadToEnd();
string[] file = parts.Split(new string[] { Environment.NewLine }, StringSplitOptions.None);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < file.Length; i++)
{
string[] data = file[i].Split(new string[] { "," }, StringSplitOptions.None);
unsortedDates.Add(data[1]);
}
var sortedDatesAscending = unsortedDates.OrderBy(x => DateTime.ParseExact(x, "dd/MM/yyyy", null));
foreach (string s in sortedDatesAscending)
{
sb.AppendLine(s + "<br />");
Label1.Text = sb.ToString();
}

Algorithm for filtering top-level directories among a list of paths, C#

Input:
/dir1
/dir1/subdir
/dir1/subdir/sub-subdir
/dir2
Output should be:
/dir1
/dir2
How about this:
string inputDir = "/dir1/subdir/sub-subdir";
string [] Split = inputDir.Split(new Char [] {'/'}, StringSplitOptions.RemoveEmptyEntries);
string outputDir = Split[0];
List<string> result= new List<string>();
foreach (string i in input)
{
string[] tmp = i.split(#"/");
result.add(#"/" + tmp[0]);
}

Why is this code not replacing data in a text file?

I'm working on a small app which should read a file (ANSI 835) and replace data at certain positions with generic data. Basically I'm trying to scrub a person's first and last name from the file.
The line I'm searching for that contains the name looks like this:
NM1*QC*1*Doe*John*R***MI*010088307 01~
My code looks like this:
string[] input_file = (string[])(e.Data.GetData(DataFormats.FileDrop));
string output_file = #"c:\scrubbed.txt";
foreach (string file in input_file)
{
string[] lines = File.ReadAllLines(file);
foreach (string line in lines)
{
if (line.StartsWith("NM1*QC"))
{
line.Split('*')[1] = "Lastname";
line.Split('*')[2] = "Firstname";
}
}
File.WriteAllLines(output_file, lines);
}
The File.WriteAllLines works, but the data isn't being changed. I'm trying to get any line that starts with NM1*QC to look like this:
NM1*QC*1*Lastname*Firstname*R***MI*010088307 01~
There are many lines in the file that start with NM1*QC. What's the proper way to 'find and replace' and then create a new file in this situation?
As always, thanks for your time!
The calls to String.Split return variables that you neither capture, nor use, they do not change the underlying string. So your code equates to this:
if (line.StartsWith("NM1*QC"))
{
string[] split1 = line.Split('*')[1] = "Lastname";
string[] split2 = line.Split('*')[2] = "Firstname";
}
You would need to take the results of split1 and split2 and use those to recreate your string. Here is how I would re-write your code:
string[] input_file = (string[])(e.Data.GetData(DataFormats.FileDrop));
string output_file = #"c:\scrubbed.txt";
foreach (string file in input_file)
{
string[] lines = File.ReadAllLines(file);
for (int i=0; i < lines.length; i++)
{
string line = lines[i];
if (line.StartsWith("NM1*QC"))
{
string[] values = line.Split('*');
values[1] = "Lastname";
values[2] = "Firstname";
lines[i] = String.Join("*", values);
}
}
File.WriteAllLines(output_file, lines);
}
Notice I am recombining the individual values using the String.Join method, and inserting the new string back into the array of lines. That will then get written out as you expect.
Here you are creating a temporary array:
line.Split('*')
And you are changing its contents:
line.Split('*')[1] = "Lastname";
After the line has been executed the reference to this temporary array is lost and along with it go your changes.
In order to persist the changes you need to write directly to lines:
for (var i = 0; i < lines.Length; ++i)
{
var line = lines[i];
if (!line.StartsWith("NM1*QC"))
{
continue;
}
var parts = line.Split('*');
parts[3] = "Lastname";
parts[4] = "Firstname";
lines[i] = string.Join("*", parts);
}

Categories