compare string from a list of strings - c#

i'm reading a file with 10002 lines, in each line there is a name that I want to compare with a single string, and if this string is the same, i want to add the string file to a listbox, I'm using the FILE.READLINE and then add each line to a list then I use .CONTAINS method and doesnt works also with == but that doesn work either...Any suggestions?
//This is my code:
foreach (string h in Directory.EnumerateFiles(NomDirec, "resume*"))
{
this.listBox1.Items.Add(h);
//Read Lines here and add them to a list and a listbox
var NombreLinea = File.ReadLines(h);
foreach (var item in NombreLinea)
{
NombreAbuscar.Add(item).Remove(item.IndexOf(":"));
this.listBox3.Items.Add(item);
}
//Here I want to add this file only if "NombreCompleto" is present in my resume file.
foreach (string t in Directory.EnumerateFiles(NomDirec, "ESSD1*"))
{
string[] Nombre = File.ReadLines(t).ElementAtOrDefault(6).Split(':');
string[] ApellidoPat = File.ReadLines(t).ElementAtOrDefault(7).Split(':');
string[] ApellidoMat = File.ReadLines(t).ElementAtOrDefault(8).Split(':');
string NombreCompleto = ApellidoPat[1] + ApellidoMat[1] + "," + " " + Nombre[1] + " " + ":";
foreach (var item in NombreAbuscar)
{
if (NombreCompleto == item)
{
this.listBox1.Items.Add(t);
break;
}
}
}
Could be a way to only read the a certain part of the line and add it to my listbox??

Related

How to put my C# code in string to pass to an e-mail?

I am using Mailkit to send an email.
So in the body of the email, I am passing data like this:
message.Body = new TextPart("plain")
{
foreach (var item in model.Transaction)
{
Console.WriteLine(item.Account +"-"+item.Amount+"-"+item.Date);
}
Text = #"";
};
but I wanted to put item.Account, item.Amount, item.Date in #""
How can I do that?
you should use $
$"{item.Account}, {item.Amount}, {item.Date}";
Because # is used to escaping specials symbols
You won't be able to access item.* outside of foreach*.
To create a single string from multiple strings you could use string.Join:
List<string> l = new ();
foreach (var item in model.Transaction)
{
var fromSingleItem = $"{item.Account}-{item.Amount}-{item.Date}";
l.Append(fromSingleItem);
}
var fromAllItems = string.Join(", ", l);
* = What would time outside of foreach mean? Would it be the first item's data, or the last one's, or from the middle?
I would use a string builder for this
var sb= new StringBuilder();
foreach (var item in model.Transaction)
{
sb.Append( item.Account + "-" + item.Amount.ToString() + "-"
+ item.Date.ToString() + "\n");
}
message.Body = new TextPart("plain")
{
Text = sb.ToString();
};
or if you have only several items
var sb= string.Empty;
foreach (var item in model.Transaction)
{
sb+= item.Account + "-" + item.Amount.ToString() + "-" + item.Date.ToString() + "\n");
}
Serge has the right idea, but I would tweak it a bit as there is a performance penalty every time you concatenate using the '+' symbol (a new String object is instantiated when you concatenate with '+'). I would suggest you continue to use StringBuilder even if you only have a single item in your foreach loop.
var builder = new StringBuilder();
foreach (var item in model.Transaction)
{
builder.Append(item.Account);
builder.Append("-");
builder.Append(item.Amount);
builder.Append("-");
builder.AppendLine(item.Date);
}
message.Body = new TextPart("plain")
{
Text = builder.ToString()
};

How to add a list<string> that orders file paths that are getting counted inside the cycle asp.net c#

Inside a foreach loop, i am counting and getting the full path of files with similar names, and I need to access them later so I want to make a list that saves them, and my question is how can I do this?
I´ve been trying to do it like this.
protected void ShowPng(string pathPgnImg)
{
btnNextPage.Visible = true;
string sImageName = "";
string sImagePathImages = Server.MapPath("Anexos/");
string pngFile = "";
List<string> pngs = new List<string> { pngFile };
string FileWithoutPath = Path.GetFileName(pathPgnImg);
string fileWithoutPathAndExt = Path.GetFileNameWithoutExtension(FileWithoutPath);
if(fileWithoutPathAndExt + "_pag" + LblHiddenImagePageNumber != fileWithoutPathAndExt + "_pag" + "" )
{
DirectoryInfo AnexoDirectory = new DirectoryInfo(PathForPdf);
FileInfo[] filesInDir = AnexoDirectory.GetFiles(fileWithoutPathAndExt + "_pag" + "*.png");
foreach (FileInfo foundFile in filesInDir)
{
pngFile = foundFile.FullName;
pngs = new List<string> { pngFile };
}
string sFileExt = Path.GetExtension(pngFile);
pngFile = Path.GetFileNameWithoutExtension(pngFile);
m_sImageNameUserUpload = pngFile + sFileExt;
m_sImageNameGenerated = Path.Combine(sImagePathImages, m_sImageNameUserUpload);
//Literal1.Text += "<img src=" + '"' + pngFile + '"' + "/>";
imgCrop.ImageUrl = "Anexos\\" + Path.GetFileName(pngFile);
if (m_sImageNameUserUpload != "")
{
pnlCrop.Visible = true;
imgCrop.ImageUrl = "Anexos/" + m_sImageNameUserUpload;
Session["ImageName"] = m_sImageNameUserUpload;
}
}
}
You can find what I mean in these lines here:
foreach (FileInfo foundFile in filesInDir)
{
pngFile = foundFile.FullName;
pngs = new List<string> { pngFile };
}
So what can I do? the output right now for it is although it adds the value it doesn't save it and add the other ones just adds that one to the list.
Thank you #Knoop for the answer to this simple question.
Turns out the only problem i was having was i wasn´t adding up to the list count.
So start by making a list:
List<string> Files = new List<string>;
Since i was trying to add the value of a variable that kept updating trough a foreach loop, ill use that example:
foreach (FileInfo foundFile in filesInDir)
{
pngFile = foundFile.FullName;
pngs.Add(pngFile);
}
Just to explain what i changed from the original question post to this answer was this line:
pngs.Add(pngFile);
with the name of the list and the .ADD it keeps adding the pngFile value everytime the loop restarts.
Once again thank you to #Knoop for the help.
I hope this helps some of you too.

c# Windows Form, replace string in textbox (file content) with another string

I have a textbox that contains all of the lines of a loaded file.
It looks like this:
I am able to load a specific line of the file that contains a specific string using this in the app:
How would I be able to update the file/main textbox after I press the "Edit Module" button, if any of the textboxes would be changed .
For example, I would change Exam Weighting: "0.4" to Exam Weighting: "0.6", then press the "Edit Module" button which would edit the main textbox(file content). Which then would allow me to save the file with the updated content.
This is the code I am using to get a specific line from the file based on string from a textbox:
private void editModuleButton_Click(object sender, EventArgs e)
{
citation = editModuleComboBox.Text;
citationChange();
}
private void citationChange()
{
List<string> matchedList = new List<string>();
string[] linesArr = File.ReadAllLines(fileName);
//find matches
foreach (string s in linesArr)
{
if (s.Contains(citation))
{
matchedList.Add(s); //matched
}
}
//output
foreach (string s in matchedList)
{
string citationLine = s;
string[] lineData = citationLine.Split(',');
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];
}
}
If somebody with enough rep could insert the images to this post, that would be great. Thanks
This solution might not be the perfect, but should work for you. What you need to do is whenever the Edit Module button is pressed, create a new string based on the text fields and replace it with the original line. First declare a string variable private string ChangedString = ""; inside the class, then:
foreach (string s in matchedList)
{
string citationLine = s;
string[] lineData = citationLine.Split(',');
string Stream = lineData[0]; //Store this somewhere so that it can be accessed later
string Stage = lineData[1]; //Store this somewhere so that it can be accessed later
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];
}
store Stream and Stage in any Textbox/ComboBox if you already haven't then replace them accordingly in the following line. Now in EditButton_Click [Click Event] write:
ChangedString = Stream + "," + Stage + "," + selectedModuleLabel.Text + "," + moduleTitleTextBox.Text
+ "," + creditsTextBox.Text + "," + semesterTextBox.Text + "," + examWeightingTextBox.Text + ","
+ examMarkTextBox.Text + "," + courseworkWeightingTextBox.Text + "," + courseworkMarkTexbox.Text;
Now replace this string with the original line.
Edit: As you would get the line number which is being edited, store it in a variable, let's say
int LineBeingEdited = 3 //Supposing line number three is being edited.
Then again in the same Click event you can write this:
ChangedString = Stream + "," + Stage + "," + selectedModuleLabel.Text + "," + moduleTitleTextBox.Text
+ "," + creditsTextBox.Text + "," + semesterTextBox.Text + "," + examWeightingTextBox.Text + ","
+ examMarkTextBox.Text + "," + courseworkWeightingTextBox.Text + "," + courseworkMarkTexbox.Text;
var lines = TextBox1.Lines;
lines[LineBeingEdited] = ChangedString;
TextBox1.Lines = lines;
EDIT 2: To get the line number I would suggest you to modify your for each loop to for loop. Also add a int variable to store the line number inside the class like : private int LineBeingEdited = 0;
Modify this for each :
foreach (string s in linesArr)
{
if (s.Contains(citation))
{
matchedList.Add(s); //matched
}
}
To for loop:
for (int a = 0; a < linesArr.Length; a++)
{
if (s.Contains(citation))
{
matchedList.Add(linesArr[a]); //matched
LineBeingEdited = a;
break; //breaks the loop when a match is found
}
}
The above method is being used, taking into consideration that there will always be a single match. LineBeingEdited will now have the line number and can be accessed from anywhere in the class

Reading in first line of csv file and saving to a list without using ',' split

I have a csv file that I need to read in the first line and save it to a List. Only problem is there are commas in some of the text and it is splitting in the middle of a field when I need it not to. Unfortunately I cannot change the data inside so whats there needs to stay. I currently also write the data to csv so I was thinking maybe instead of using a comma I can use a different character. Does anyone know if this is possible? I have been researching but am not coming up with a proper answer. Here is my code below:
using System;
using System.CodeDom;
using System.IO;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace TestJSON
{
class Program
{
static void Main()
{
var data = JsonConvert.DeserializeObject<dynamic>(File.ReadAllText(
#"C:\Users\nphillips\workspace\2016R23\UITestAutomation\SeedDataGenerator\src\staticresources\seeddata.resource"));
string fileName = "";
var bundles = data.RecordSetBundles;
foreach (var bundle in bundles)
{
var records = bundle.Records;
foreach (var record in records)
{
var test = record.attributes;
foreach (var testagain in test)
{
// Getting the object Name Ex. Location, Item, etc.
var jprop = testagain as JProperty;
if (jprop != null)
{
fileName = jprop.First.ToString().Split('_')[2]+ ".csv";
}
break;
}
string header = "";
string value = "";
foreach (var child in record)
{
var theChild = child as JProperty;
if (theChild != null && !theChild.Name.Equals("attributes"))
{
header += child.Name + ",";
value += child.Value.ToString() + ",";
}
}
value += "+" + Environment.NewLine;
if (!File.Exists(fileName))
{
header += "+" + Environment.NewLine;
File.WriteAllText(fileName, header);
}
else
{
// Need to read in here
var readCSV = new StreamReader(fileName);
var splits = readCSV.ReadLine();
}
File.AppendAllText(fileName, value);
}
}
}
}
}
You need to know how the file is delimited. I would guess that this file is tab delimited, so split on that instead.
Assuming your line is called myCSVLine... I.E
string seperator = "\t";
string[] splitLine = myCSVLine.Split(seperator.ToCharArray());
splitLine would now have all of your strings, including ones with commas

Best method for comparing XML with string

I am looking for the best way to compare XML data with a string.
the data is stored in a xml called test.xml, and must be compared with the name descendant, if there is a match more info from the xml must be added to a textbox and picture box.
My ( working ) code:
var xmlDocument = XDocument.Load("test.xml"); // XML koppellen
var key1 = xmlDocument.Descendants("NAME"); // XML filepath
var key2 = xmlDocument.Descendants("TITLE"); // XML titel
var key3 = xmlDocument.Descendants("BRAND"); // XML afbeelding
var key4 = xmlDocument.Descendants("TYPE"); // XML merk
var key5 = xmlDocument.Descendants("SOORT"); // XML type
var key6 = xmlDocument.Descendants("NAAM"); // XML naam
List<string> file = new List<string>();
List<string> title = new List<string>();
List<string> brand = new List<string>();
List<string> type = new List<string>();
List<string> soort = new List<string>();
List<string> naam = new List<string>();
int i = 0;
foreach (var key in key1)
{
file.Add(key.Value.Trim());
}
foreach (var key in key2)
{
title.Add(key.Value.Trim());
}
foreach (var key in key3)
{
brand.Add(key.Value.Trim());
}
foreach (var key in key4)
{
type.Add(key.Value.Trim());
}
foreach (var key in key5)
{
soort.Add(key.Value.Trim());
}
foreach (var key in key6)
{
naam.Add(key.Value.Trim());
}
foreach (var Name in naam)
{
if (textBox3.Text.ToString() == Name.ToString())
{
PDFLocation = file[i].ToString();
pictureBox1.Image = pdfhandler.GetPDFthumbNail(PDFLocation);
textBox4.Text =
title[i].ToString() + "\r\n" +
brand[i].ToString() + "\r\n" +
type[i].ToString() + "\r\n" +
soort[i].ToString() + "\r\n" +
textBox3.Text + "\r\n";
}
i++;
}
]
I think this is not the best way to do it, but cant see a better way....
Update: solution:
foreach (XElement element in xmlDocument.Descendants("PDFDATA"))
{
if (textBox3.Text.ToString() == element.Element("NAAM").Value.Trim())
{
PDFLocation = element.Element("NAME").Value.ToString();
pictureBox1.Image = pdfhandler.GetPDFthumbNail(PDFLocation);
textBox4.Text =
element.Element("TITLE").Value + "\r\n" +
element.Element("BRAND").Value + "\r\n";
break;
}
}
Instead of thinking of the xml and a bunch of individual lists of data, it helps to think of it more as objects. Then you can loop through each element one at a time and don't need to split it up into individual lists. This not only removes duplicate code but more importantly creates a better abstraction of the data you are working with. This makes it easier to read and understand what the code is doing.
foreach (XElement element in xmlDocument.Elements())
{
if (textBox3.Text.ToString() == element.Element("NAAM").Value)
{
PDFLocation = element.Element("NAAM").Value;
pictureBox1.Image = pdfhandler.GetPDFthumbNail(PDFLocation);
textBox4.Text =
element.Element("Title").Value + "\r\n" +
element.Element("Brand").Value + "\r\n" +
element.Element("Type").Value + "\r\n"
// access rest of properties...
}
}

Categories