I have a list with many line extracted from file and I want to display it a richTextbox with this code
foreach (string s in Dettaglio)
{
txtDettaglio.Text += s + Environment.NewLine;
}
And Dettaglio definition is:
System.Collections.Generic.List<string> Dettaglio = new System.Collections.Generic.List<string>();
But it makes a lot of time to accomplish it there’s any other solution or I haven’t to use richTextbox?
Firstly: I'd use AppendText instead of string concatenation:
foreach (string s in Dettaglio)
{
txtDettaglio.AppendText(s);
txtDettaglio.AppendText(Environment.NewLine);
}
It may be faster to use concatenation to avoid calling AppendText twice:
foreach (string s in Dettaglio)
{
txtDettaglio.AppendText(s + Environment.NewLine);
}
Now it could be that that won't actually be any faster, but it's what I'd try to start with - the internal data structure of RichTextBox may need to do work in order to fetch the Text property, and using AppendText you may avoid it having to reparse text that it's already handled.
Maybe using StringBuilder will be faster
StringBuilder sb = new StringBuilder();
foreach (string s in Dettaglio)
{
sb.Append(s + Environment.NewLine);
}
txtDettaglio.Text = sb.ToString();
Related
I have this code:
System.IO.Directory.CreateDirectory(foldercreationPATH.Text + "\\Tosystem\\" + customersBOX.Text);
Now, if user specifies folder(names) to be created separated by comma, how can I do it?
E.g. if textbox contains "customer1, customer2", then I would like to create separate folders for these.
You would take the string inside the textbox and use the
.split()
method to create an array which you can loop through using a
foreach
loop. I also invoked the
.Trim()
method to remove any trailing white space.
string[] strArr = customersBOX.Text.Split(',');
foreach (string item in strArr)
{
item.Trim();
System.IO.Directory.CreateDirectory(foldercreationPATH.Text + "\\Tosystem\\" + item);
}
you can try this.
var dirs = customersBOX.Text.Split(",".ToArray(), StringSplitOptions.RemoveEmptyEntries);
foreach (var dir in dirs)
{
var finalPath = Path.Combine(foldercreationPATH.Text, "Tosystem", dir);
Directory.CreateDirectory(finalPath);
}
This is a bit of an odd question, and I'm sure there was an easier way of doing this but...
I have a method that returns a List of names. I am parsing through this list with a foreach loop. I am adding each name to one long String so that I can set the text of a Table Cell to that string. But I can't seem to get it to add a new line. Is this possible?
Here's a snippet of the code:
Earlier my table loop:
TableCell tempCell = new TableCell();
The issue:
// Returns a List of Employees on the specified day and time.
List<string> EmployeeList = CheckForEmployees(currentDay, timeCount);
string PrintedList = "";
foreach (String s in EmployeeList)
{
PrintedList += s;
// PrintedList += s + System.Environment.NewLine;
// PrintedList += s + " \n";
}
tempCell.Text = PrintedList;
Both the commented code lines didn't work. Any ideas?
You need to append a break tag since you want the new line to show in HTML. So append <br/>. I would also recommend using a stringbuilder if it is more than a few iterations.
Table cell as in HTML table cell? Do you perhaps need to use the "br" tag instead of normal newline?
Another thing, you should use StringBuilder instead of doing string concatenation the way you do. Or even better, String.Join.
string PrintedList = String.Join("br-tag", EmployeeList);
Again, not sure if the br-tag is what you are after, but prefer to use the methods in the String class when possible.
The code below read a text file with a header of a path and followed by a list of file names.
the code adds each file (from the second line and on) to a ListView.
For some reason the last two lines are never reached.
Any ideas?
private void loadFromFile()
{
if ((faxInOn != null) && File.Exists(#"D:\Settings.ye"))
{
string[] s;
StreamReader sr = new StreamReader(#"D:\Settings.ye", Encoding.Default);
s = sr.ReadToEnd().Split(new string[] { "\r\n", "\n" }, StringSplitOptions.None);
faxInOn.changePath(s[0]);
foreach (string temp in s)
foreach (ListViewItem lvi in listView1.Items)
if (lvi.Text == temp.Substring(1))
lvi.ImageIndex = int.Parse(temp.Substring(0, 1));
sr.Close();
sr.Dispose();
}
}
Thanks
The way the foreach blocks are used are really inefficient for what I think you are trying to do. Also, it would be much easier and cleaner for you to use the "using(...)" block so your resources are properly cleaned up and handled correctly. Please see: http://msdn.microsoft.com/en-us/library/yh598w02.aspx
Try using File.ReadLines
For example:
// Read all lines in file, skipping the first header line
foreach(var line in File.ReadLines(#"D:\Settings.ye").Skip(1))
{
// add to list view
}
Trying to make a list out of a string of part names. It's skipping displaying all the names except the very last one in the list.. Why is it doing this? Is there a better way of doing this?
My Code behind
List<string> Ta1PartNumbers = ta1input.Split('\n').ToList<string>(); //Trying to split at the line break.. Would this be the proper way to do it?
foreach (string Tpartnumber in TramPartNumbers)
{
Div1.InnerText = (Tpartnumber);
}
List is like so:
Part_numbers
1017foo
1121bar
etc..
You're resetting the innerText value each iteration of the loop, so it only retains the last one. Try appending with the += operator
foreach (string Tpartnumber in TransimPartNumbers)
{
Div1.InnerHtml += Tpartnumber + "<br />";
}
I'd avoid using a List where you don't need to. Use this split method instead, but I think you want \r\n... And like the other posters, you needed += which appends, rather than + which updates.
string[] lines = Regex.Split(ta1input, "\r\n");
foreach (string line in lines)
{
Div1.InnerText += Tpartnumber;
}
I make this mistake more than I should. Try:
Div1.InnerText = "";
foreach (string Tpartnumber in TransimPartNumbers)
{
Div1.InnerText += (Tpartnumber);
}
You are basically overwriting the previous value each time.
Each iteration of your loop replaces the InnerText of Div1 with the current string. This is why you are only getting the last string, you wrote over all the previous strings.
But, why even split the string? If you just want to write all of the strings to the div, you can just do:
Div1.InnerText = ta1Input;
What do you want as your final HTML?
Part_numbers<br/>
1017foo<br/>
1121bar<br/>
etc..<br/>
Or
<div>Part_numbers</div>
<div>1017foo</div>
<div>1121bar</div>
<div>etc..</div>
Or something else? Personally, I prefer the latter. I'd do something like this:
string[] Ta1PartNumbers = ta1input.Split('\n');
foreach (string Tpartnumber in Ta1PartNumbers)
{
var div = new HtmlGenericControl("div");
div.InnerText = Tpartnumber;
Div1.Controls.Add(div);
}
what i'm basically trying to do is compare two HUGE text files and if they match write out a string, i have this written but it's extremely slow. I was hoping you guys might have a better idea. In the below example i'm comparing collect[3] splitfound[0]
string[] collectionlist = File.ReadAllLines(#"C:\found.txt");
string[] foundlist = File.ReadAllLines(#"C:\collection_export.txt");
foreach (string found in foundlist)
{
string[] spltifound = found.Split('|');
string matchfound = spltifound[0].Replace(".txt", ""); ;
foreach (string collect in collectionlist)
{
string[] splitcollect = collect.Split('\\');
string matchcollect = splitcollect[3].Replace(".txt", "");
if (matchcollect == matchfound)
{
end++;
long finaldest = (start - end);
Console.WriteLine(finaldest);
File.AppendAllText(#"C:\copy.txt", "copy \"" + collect + "\" \"C:\\OUT\\" + spltifound[1] + "\\" + spltifound[0] + ".txt\"\n");
break;
}
}
}
Sorry for the vagueness guys,
What I'm trying to do is simply say if content from one file exists in another write out a string(the string isn't important, merely the time to find the two comparatives is). collectionlist is like this:
Apple|Farm
foundlist is like this
C:\cow\horse\turtle.txt
C:\cow\pig\apple.txt
what i'm doing is taking apple from collectionlist, and finding the line that contains apple in foundlist. Then writing out a basic windows copy batch file. Sorry for the confusion.
Answer(All credit to Slaks)
string[] foundlist = File.ReadAllLines(#"C:\found.txt");
var collection = File.ReadLines(#"C:\collection_export.txt")
.ToDictionary(s => s.Split('|')[0].Replace(".txt",""));
using (var writer = new StreamWriter(#"C:\Copy.txt"))
{
foreach (string found in foundlist)
{
string[] splitFound = found.Split('\\');
string matchFound = Path.GetFileNameWithoutExtension(found);
string collectedLine;
if (collection.TryGetValue(matchFound,out collectedLine))
{
string[] collectlinesplit = collectedLine.Split('|');
end++;
long finaldest = (start - end);
Console.WriteLine(finaldest);
writer.WriteLine("copy \"" + found + "\" \"C:\\O\\" + collectlinesplit[1] + "\\" + collectlinesplit[0] + ".txt\"");
}
}
}
Call File.ReadLines() (.NET 4) instead of ReadAllLines() (.NET 2.0).
ReadAllLines needs to build an array to hold the return value, which can be extremely slow for large files.
If you're not using .Net 4.0, replace it with a StreamReader.
Build a Dictionary<string, string> with the matchCollects (once), then loop through the foundList and check whether the HashSet contains matchFound.
This allows you to replace the O(n) inner loop with an O(1) hash check
Use a StreamWriter instead of calling AppendText
EDIT: Call Path.GetFileNameWithoutExtension and the other Path methods instead of manually manipulating strings.
For example:
var collection = File.ReadLines(#"C:\found.txt")
.ToDictionary(s => s.Split('\\')[3].Replace(".txt", ""));
using (var writer = new StreamWriter(#"C:\Copy.txt")) {
foreach (string found in foundlist) {
string splitFound = found.Split('|');
string matchFound = Path.GetFileNameWithoutExtension(found)
string collectedLine;
if (collection.TryGetValue(matchFound, collectedLine)) {
end++;
long finaldest = (start - end);
Console.WriteLine(finaldest);
writer.WriteLine("copy \"" + collectedLine + "\" \"C:\\OUT\\"
+ splitFound[1] + "\\" + spltifound[0] + ".txt\"");
}
}
}
First I'd suggest normalizing both files and putting one of them in a set. This allows you to quickly test whether a specific line is present and reduces the complexity from O(n*n) to O(n).
Also you shouldn't open and close the file every time you write a line:
File.AppendAllText(...); // This causes the file to be opened and closed.
Open the output file once at the start of the operation, write lines to it, then close it when all lines have been written.
You have a cartesian product, so it makes sense to index one side instead of doing an enhaustive linear search.
Extract the keys from one file and use either a Set or SortedList data structure to hold them. This will make the lookups much much faster. (Your overall algorithm will be O(N lg N) instead of O(N**2) )