Display lins from text.file to array c# - c#

I am trying to read lines from txt file into array and display it into a text box.
Here is my code:
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack != true)
{
blogPostTextBox.Text ="";
string blogFilePath = Server.MapPath("~") + "/Blogs.txt";
string[] blogMessageArray = File.ReadAllLines(blogFilePath);
// this for loop code does not work..I think..
for (int i = 0; i < blogMessageArray.Length; i++)
{
string[] fileLineArray = blogMessageArray[i].Split(' ');
blogPostTextBox.Text = blogMessageArray[i] + System.Environment.New Line.ToString();
}
}
}
My text file contains several line and I am trying to split each line to array and display all lines into a text box using a for loop or while loop.

UPDATE:
For ASP.Net
var items =File.ReadAllLines(blogFilePath).SelectMany(line => line.Split()).Where(x=>!string.IsNullOrEmpty(x));
blogPostTextBox.Text=string.Join(Environment.NewLine, items)
and as a side note, it is better to use Path.Combine when you build path from multiple strings
string blogFilePath = Path.Combine( Server.MapPath("~") , "Blogs.txt");
also if (IsPostBack != true) is valid but you can do as
if (!IsPostBack)
Winform
If the Multiline property of the text box control is set to true, you can use TextBoxBase.Lines Property
blogPostTextBox.Lines =File.ReadAllLines(blogFilePath);
if you need to split each line and set as textbox text then
blogPostTextBox.Lines = File.ReadAllLines(blogFilePath).SelectMany(line => line.Split()).ToArray();

You have to set TextMode="MultiLine" in your TextBox(default value is SingleLine), then you could build the text with Linq in this way:
var allLinesText = blogMessageArray
.SelectMany(line => line.Split().Select(word => word.Trim()))
.Where(word => !string.IsNullOrEmpty(word));
blogPostTextBox.Text = string.Join(Environment.NewLine, allLinesText);

You need to append each line to the textbox. What you are doing above is overwriting the contents of the textbox with each new line.
string[] blogMessageArray = File.ReadAllLines("");
blogPostTextBox.Text = "";
foreach (string message in blogMessageArray)
{
blogPostTextBox.Text += message + Environment.NewLine;
}
Although rather than read in all the lines, and then write out all the lines, why don't you just write out all the text to the textbox?
blogPostTextBox.Text = File.ReadAllText();

Though you could do this in a loop, you really don't need to (or want to)
Replace your loop with with built in dot net methods that actually do what your need.
See String.Join()
public static string Join(
string separator,
params string[] value
)
This will combine all of the elements of blogMessageArray with your specified separator
('\n' in your case, HTML does not need "\r\n")
Then just assign this to the property blogPostTextBox.Tex

Related

How would I access a txt file and split the links

Alright, I have a program that grabs links off of a website and puts it into a txt BUT the links aren't separated onto their own lines and I need to somehow do that without having to manually do it myself, here is the code used to grab the links off of the website, write the links to a text file then grab the txt file and read it.
private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
var client = new WebClient();
string text = client.DownloadString("https://currentlinks.com");
File.WriteAllText("C:/ProgramData/oof.txt", text);
string searchKeyword = "https://foobar.to/showthread.php";
string fileName = "C:/ProgramData/oof.txt";
string[] textLines = File.ReadAllLines(fileName);
List<string> results = new List<string>();
foreach (string line in textLines)
{
if (line.Contains(searchKeyword))
{
results.Add(line);
}
var sb = new StringBuilder();
foreach (var item in results)
{
sb.Append(item);
}
textBox1.Text = sb.ToString();
var parsed = textBox1;
TextWriter tw = new StreamWriter("C:/ProgramData/parsed.txt");
// write lines of text to the file
tw.WriteLine(parsed);
// close the stream
tw.Close();
}
}
You are getting all the Links (URLs) in one single string. There is not straight forward way to get all the URLs individually without some assumptions.
With the sample data you shared, I assume that the URLs in the string follow simple URLs format and do not have any fancy stuff in it. They start with http and one url does not have any other http.
With above assumptions, I suggest following code.
// Sample data as shared by the OP
string data = "https://forum.to/showthread.php?tid=22305https://forum.to/showthread.php?tid=22405https://forum.to/showthread.php?tid=22318";
//Splitting the string by string `http`
var items = data.Split(new [] {"http"},StringSplitOptions.RemoveEmptyEntries).ToList();
//At this point all the strings in items collection will be without "http" at the start.
//So they will look like as following.
// s://forum.to/showthread.php?tid=22305
// s://forum.to/showthread.php?tid=22405
// s://forum.to/showthread.php?tid=22318
//So we need to add "http" at the start of each of the item as following.
items = items.Select(i => "http" + i).ToList();
// After this they will become like following.
// https://forum.to/showthread.php?tid=22305
// https://forum.to/showthread.php?tid=22405
// https://forum.to/showthread.php?tid=22318
//Now we need to create a single string with newline character between two items so
//that they represent a single line individually.
var text = String.Join("\r\n", items);
// Then write the text to the file.
File.WriteAllText("C:/ProgramData/oof.txt", text);
This should help you resolve your issue.
.Split way
Could you use yourString.Split("https://");?
Example:
//This simple example assumes that all links are https (not http)
string contents = "https://www.example.com/dogs/poodles/poodle1.htmlhttps://www.example.com/dogs/poodles/poodle2.html";
const string Prefix = "https://";
var linksWithoutPrefix = contents.Split(Prefix, StringSplitOptions.RemoveEmptyEntries);
//using System.Linq
var linksWithPrefix = linksWithoutPrefix.Select(l => Prefix + l);
foreach (var match in linksWithPrefix)
{
Console.WriteLine(match);
}
Regex way
Another option is to use reg exp.
Failed - cannot find/write the right regex ... got to go now
string contents = "http://www.example.com/dogs/poodles/poodle1.htmlhttp://www.example.com/dogs/poodles/poodle2.html";
//From https://regexr.com/
var rgx = new Regex(#"(?<Protocol>\w+):\/\/(?<Domain>[\w#][\w.:#]+)\/?[\w\.?=%&=\-#/$,]*");
var matches = rgx.Matches(contents);
foreach(var match in matches )
{
Console.WriteLine(match);
}
//This finds 'http://www.example.com/dogs/poodles/poodle1.htmlhttp' (note the htmlhttp at the end

How to load particular texts of text file to particular textboxes

I have created a project in C# windows form application. I am using .Net framework version 4.0 and Visual studio 2010.
Project contains Save and load File button. And also some textboxes.
I created a text file like this
Serial Number = 1
Type Number = 500
Test Engineer = jay
Date = 03/05/2018
Time = 16:17:20 PM
Test1 = 1.00
Test2 = 1.76
.
.
.
Test18 = 4.66
Code for Load File button:
private void btn_LoadFile_Click(object sender, EventArgs e)
{
OpenFileDialog fdlg = new OpenFileDialog();
if (fdlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
System.IO.StreamReader sr = new
System.IO.StreamReader(fdlg.FileName);
string[] lines = sr.ReadToEnd().Split('\n');
tb_SerialNo.Text = lines[0];
tb_TypeNo.Text = lines[1];
tb_TestEngineer.Text = lines[2];
tb_Date.Text = lines[3];
tb_Test1.Text = lines[4];
tb_Test2.Text = lines[5];
}
}
When I run above code, I got value in Serial no textbox is Serial Number = 1 but I want 1in textbox. Same Type Number Tex box Type Number = 500 but here also I want 500 in Type number textbox.
When you split by new line, lines[0] will store Serial Number = 1. Here you need to split it again by =.
If you try and print values of each element from string array, you will understand what changes you need to do in your code.
private void btn_LoadFile_Click(object sender, EventArgs e)
{
OpenFileDialog fdlg = new OpenFileDialog();
if (fdlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
System.IO.StreamReader sr = new
System.IO.StreamReader(fdlg.FileName);
string[] lines = sr.ReadToEnd().Split('\n'); //To make your code more readable, you can use "Environment.NewLine" instead of '\n'
Console.WriteLine(lines[0]); //Here it will give "Serial Number = 1"
// you need to store 1 in tb_SerialNo.Text, so split lines[0] with =
//Have you tried with this.
string[] splitWithEqualTo = lines[0].Split('=');
tb_SerialNo.Text = splitWithEqualTo [1];
//Similar kind of logic you can apply for other text boxes.
}
}
To fix your issue, you can try with the followings
Console.WriteLine(lines[0]); // This will print "Serial Number = 1"
string[] slitLine = lines[0].Split('=');
Console.WriteLine(slitLine[0]); //This will print "Serial Number"
Console.WriteLine(slitLine[1]); //This will print 1, this is what you need to store in tb_SerialNo.Text, right?
This is not the solution, but you will understand what changes you need to do in your code.
private void btn_LoadFile_Click(object sender, EventArgs e)
{
OpenFileDialog fdlg = new OpenFileDialog();
if (fdlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
System.IO.StreamReader sr = new
System.IO.StreamReader(fdlg.FileName);
string[] lines = sr.ReadToEnd().Split('\n');
PrintText(tb_SerialNo, lines[0]);
PrintText(tb_TypeNo , lines[1]);
PrintText(tb_TestEngineer, lines[2]);
PrintText(tb_Date, lines[3]);
PrintText(tb_Test1, lines[4]);
PrintText(tb_Test2, lines[5]);
}
}
private void PrintText(TextBox control, string line)
{
var splitline = line.Split('=');
control.Text = splitline[1];
}
try this
You could use string.Split() or string.LastIndexOf() to extract the part you need from the original string.
For example:
Here, we split the string in two when a '=' char is found. The extra space is lifted by Trim(), which is used to remove white spaces from the leading and trailing parts of a string.
tb_Test2.Text = lines[5].Split('=').Last().Trim();
or
LastIndexOf() finds the symbol specified, starting its search from the end of a string and returns its position (if it finds it, otherwise -1).
Substring() generates a new string from the supplied one, starting from a position and taking a specified number of characters.
Here, starting from the index returned by LastIndexOf() and including all the characters to the end of the string (if you don't specify how many characters it has to take, it takes them all. It's a method overload).
tb_Date.Text = lines[3].Substring(lines[3].LastIndexOf("=") + 1).TrimStart();
In both cases, the original string remains untouched.
You can also create a new array from the original one, containing only the required parts and then assign the values of the new array:
string[] lines2 = lines.Select(s => s.Split('=').Last().Trim()).ToArray();
tb_SerialNo.Text = lines2[0];
tb_TypeNo.Text = lines2[1];
//(...)

Select Text in a multiline textbox, move it to another multiline textbox on a button click in C#

I have a problem that I haven't come across yet that I hope some of you may help me with. I am trying to select a single line, either the fist, second, or last line in a multiline textbox and move it to another multiline textbox with a button click in C#. I am unsure how to select just a single line at a time, then add it to the other multiline textbox. If anyone has some insight, that would be great! Thank you!
Brent
Well, assuming that you are defining a "line" as a complete string of characters separated by other similar strings with a newline character, and not simply as the string of characters visible in a single horizontal plane in a text field with word wrap property set to true.....
public void Button1_Click(object sender, ClickEventArgs e)
{
//get the values of both boxes
string value1 = TextBox1.Text.Trim();
string value2 = TextBox2.Text.Trim();
//split the value from the source box on its new line characters
string[] parts = value1.split(Environment.NewLine);
string last_line = parts[parts.length -1];
//add the last row from the source box to the destination box
value2 += (Environment.NewLine + last_line);
//set the last_line in the source to an empty string
parts[parts.Length -1] = String.Empty;
//put the new values back in their text boxes
TextBox1.Text = String.Join(Environment.NewLine, parts).Trim();
TextBox2.Text = value2;
}
If you are dealing with visible line and word wrapped that is a whole 'nother ball game and the answer is dependant on if you are talking ASP, or Win App. Also, this was written off the cuff, so you may need to tweak a character or two to get it to compile. No Warranties, LOL.
Something like this will work:
public void Button1_Click(object sender, ClickEventArgs e)
{
string text = TextBox1.Text;
// spliting text on the basis on newline.
string[] myArray = text.Split(new char[] { '\n' });
foreach (string s in myArray)
{
//Line by line copy
TextBox2.Text += s;
}
}
Try something like this:
private void button1_Click(object sender, EventArgs e)
{
if (textBox1.Lines.Length > 0)
{
textBox2.Text += textBox1.Lines[textBox1.GetLineFromCharIndex(textBox1.SelectionStart)];
}
}
What it is doing is using the GetLineFromCharIndex with the SelectionStart caret location as the char Index to pull the Line out of the TextBox.Lines array

how to display comma separated values in different labels after splitting them in asp.net?

i have comma separated values like English,Science in lblsubject.text which i am separating using the code below.
The code given below displays Science in both the Label1 as well as Label2 as it gets overridden...but I want to display English in one label and science in another label.
how to do it...pls help..!
string[] lines = Regex.Split(lblsubject.Text, ",");
foreach (string line in lines)
{
Label1.Text = line;
Label2.Text = line;
}
You will get two elements in the array, why are you using the foreach loop. you can do
Label1.Text = lines[0];
Label2.Text = lines[1];
You might want to add labels dynamically, if you don't know how many there will be. (Note also, Regex.Split is overkill for this, you could just use the String.Split extension method.)
string[] lines = lblsubject.Text.Split(',');
for (int i=0 ; i<lines.Length ; i++)
{
var newLabel = new Label();
newLabel.Text = lines[i];
form1.Controls.Add(newLabel);
}
Where form1 could be any container control that you want to add your labels to.
Another alternative could be to add HTML directly to your output. Something like this:
var html = string.Join("<br/>",
lblsubject.Text.Split(',').Select(
category => string.Format("<div>{0}</div>", category)
)
);
panel1.Controls.Add(new LiteralControl(html));
(Where again, panel1 is just a container for your output.)
Edit, per comment
DrowDownList1.Items.AddRange(
lblsubject.Text.Split(',')
.Select(category => new ListItem(category))
.ToArray()
);
Use Split() function
string[] lines = lblsubject.Text.Split(',');
Label1.Text = lines[0];
Label2.Text = lines[1];

C# get text from file between two hashes

In my C# program (at this point) I have two fields in my form. One is a word list using a listbox; the other is a textbox. I have been able to successfully load a large word list into the listbox from a text file. I can also display the selected item in the listbox into the textbox this way:
private void wordList_SelectedIndexChanged(object sender, EventArgs e)
{
string word = wordList.Text;
concordanceDisplay.Text = word;
}
I have another local file I need to get at to display some of its contents in the textbox. In this file each headword (as in a dictionary) is preceded by a #. So, I would like to take the variable 'word' and search in this local file to put the entries into the textbox, like so:
#headword1
entry is here...
...
...
#headword2
entry is here...
...
...
#headword3
entry is here...
...
...
You get the format of the text file. I just need to search for the correct headword with # before that word, and copy all info from there until the next hash in the file, and place it in the text box.
Obviously, I am a newbie, so be gentle. Thanks much.
P.S. I used StreamReader to get at the word list and display it in the listbox like so:
StreamReader sr = new StreamReader("C:\\...\\list-final.txt");
string line;
while ((line = sr.ReadLine()) != null)
{
MyList.Add(line);
}
wordList.DataSource = MyList;
var sectionLines = File.ReadAllLines(fileName) // shortcut to read all lines from file
.SkipWhile(l => l != "#headword2") // skip everything before the heading you want
.Skip(1) // skip the heading itself
.TakeWhile(l => !l.StartsWith("#")) // grab stuff until the next heading or the end
.ToList(); // optional convert to list
string getSection(string sectionName)
{
StreamReader sr = new StreamReader(#"C:\Path\To\file.txt");
string line;
var MyList = new List<string>();
bool inCorrectSection = false;
while ((line = sr.ReadLine()) != null)
{
if (line.StartsWith("#"))
{
if (inCorrectSection)
break;
else
inCorrectSection = Regex.IsMatch(line, #"^#" + sectionName + #"($| -)");
}
else if (inCorrectSection)
MyList.Add(line);
}
return string.Join(Environment.NewLine, MyList);
}
// in another method
textBox.Text = getSection("headword1");
Here are a few alternate ways to check if the section matches, in rough order of how accurate they are in detecting the right section name:
// if the separator after the section name is always " -", this is the best way I've thought of, since it will work regardless of what's in the sectionName
inCorrectSection = Regex.IsMatch(line, #"^#" + sectionName + #"($| -)");
// as long as the section name can't contain # or spaces, this will work
inCorrectSection = line.Split('#', ' ')[1] == sectionName;
// as long as only alphanumeric characters can ever make up the section name, this is good
inCorrectSection = Regex.IsMatch(line, #"^#" + sectionName + #"\b");
// the problem with this is that if you are searching for "head", it will find "headOther" and think it's a match
inCorrectSection = line.StartsWith("#" + sectionName);

Categories