I have written a code for extracting number from a text file using a windows From. Problem is that, Output Occurs in a partial way. Either the First Line is Printing or the Last Line. I want all the line that is containing the number
(i.e) If the text file contains,
Auto 2017
Mech 2056
CSE 2016
I want only those 2017, 2056, 2016 to be printed.
Here is the code:
private void button1_Click(object sender, EventArgs e)
{
string infile = textBox1.Text;
StreamReader sr = new StreamReader(infile);
string allDetails = File.ReadAllText(infile);
string result = Regex.Match(allDetails, #"\d+").Value;
richTextBox1.Text = result.ToString();
}
You are try to grab numeric value. Regex.Matches Will help you to solve your problem.
Below is simplified code.
private void button1_Click(object sender, EventArgs e)
{
string filedetails = File.ReadAllText(textBox1.Text);
var regexCollection = Regex.Matches(filedetails, #"\d+");
foreach (Match rc in regexCollection)
richTextBox1.AppendText(rc.Value + ",");
}
You can do this way, if you want output 2017,2056,2016
private void button1_Click(object sender, EventArgs e)
{
string infile = textBox1.Text;
string[] lines = System.IO.File.ReadAllLines(infile);
string temp = "";
int i = 0;
foreach (string line in lines)
{
string result = Regex.Match(line, #"\d+").Value;
if (i == 0)
{
temp = result;
}
else
{
temp = temp + "," + result;
}
i++;
}
richTextBox1.Text = temp;
}
or if you want single value 2017 2056 2016 then
private void button1_Click(object sender, EventArgs e)
{
string infile = textBox1.Text;
string[] lines = System.IO.File.ReadAllLines(infile);
foreach (string line in lines)
{
string result = Regex.Match(line, #"\d+").Value;
richTextBox1.Text = result ;
}
}
You need to use the method. Regex.Matches. Matches method searches the specified input string for all occurrences of a regular expression.
Match method returns the first match only, Subsequent matches need to be retrieved.
private void button1_Click(object sender, EventArgs e)
{
string infile = textBox1.Text;
StreamReader sr = new StreamReader(infile);
string allDetails = File.ReadAllText(infile);
var regexMatchCollection = Regex.Matches(allDetails, #"\d+");
foreach(Match mc in regexMatchCollection)
{
richTextBox1.AppendText(mc.Value);
richTextBox1.AppendText(",");
}
}
test.txt has
Auto 2017
Mech 2056
CSE 2016
in the following program File.ReadAllLines will store every line in a string array separately.Then we will use foreach loop to read single line at a time and store the extracted numbers in list e.g 2017 and finally with string.Join we will join the array and separate each word with "," and save it in string
List<string> list = new List<string>();
var textfile = File.ReadAllLines(#"D:\test.txt");
foreach (var line in textfile)
{
string result = Regex.Match(line, #"\d+").Value;
list.Add(result);
}
string numbers = string.Join(",",list.ToArray());
the output value will be
2017,2056,2016
private void button1_Click(object sender, EventArgs e)
{
string infile = textBox1.Text;
StreamReader sr = new StreamReader(infile);
string allDetails = File.ReadAllText(infile);
string result = string.Empty;
foreach (var item in Regex.Matches(allDetails, #"\d+"))
{
result = result + item.ToString() + ",";
}
richTextBox1.Text = result.TrimEnd(',');
}
Without using Regex,below is the simplified code
private void button1_Click(object sender, EventArgs e)
{
StringBuilder numbers = new StringBuilder();
string allDetails = File.ReadAllText(textBox1.Text);
foreach(string word in allDetails.Split(' '))
{
int number;
if(int.TryParse(word, out number))
{
numbers.Append(number);
numbers.Append(",");
}
}
richTextBox1.Text = numbers.Trim(',');
}
static void Main(string[] args)
{
string[] lines = System.IO.File.ReadAllLines(#"C:\Users\admin\Desktop\ConsoleApplication1\ConsoleApplication1\txtFile.txt");
List<string> Codelst = new List<string>();
foreach (var item in lines)
{
var a= Regex.Match(item, #"\d+").Value;
Codelst .Add(a);
}
var r = Codelst;
}
Output is like this:
Related
I am new to using the DataGridView component, I've used it once before and have managed to complete this exact task but I forgot how I achieved it.
Basically I would like to read the values from a text file which is formatted like so:
line 1,
line 2,
line 3
Here is the code I currently have:
List<string> tokens = new List<string>();
private void dataGridView1_DragDrop(object sender, DragEventArgs e)
{
string[] lines = (string[])e.Data.GetData(DataFormats.FileDrop, false);
foreach (var line in lines)
{
using (StreamReader sr = new StreamReader(Path.GetFullPath(line)))
{
var l = sr.ReadLine();
string[] data;
while (l != null)
{
data = l.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
l = sr.ReadLine();
tokens.Add(l);
}
}
}
for (int i = 0; i < tokens.Count - 1; i++)
{
dataGridView1.Rows[i].Cells[0].Selected = true;
dataGridView1.CurrentCell.Value = tokens[i];
}
}
The current code results in the line 2 being added to the datagridview only, with nothing else.
I would like to add each line into the first column of each row, depending on how many lines are in the text file.
Hopefully this makes sense, thanks a lot!
You can try this:
private void dataGridView1_DragDrop(object sender, DragEventArgs e)
{
dataGridView1.Columns.Add("Value", "Value");
var files = (string[])e.Data.GetData(DataFormats.FileDrop, false);
foreach ( var file in files )
{
var lines = File.ReadAllLines(Path.GetFullPath(file));
foreach ( string line in lines )
dataGridView1.Rows.Add(line.TrimEnd(','));
}
}
private void dataGridView1_DragEnter(object sender, DragEventArgs e)
{
if ( e.Data.GetDataPresent(DataFormats.FileDrop) )
e.Effect = DragDropEffects.Move;
else
e.Effect = DragDropEffects.None;
}
I want to make a program that counts as example the word "Me" from a richtextbox. How is this possible in c#. The code that i already have is that it loads a textfile.
private void button1_Click(object sender, EventArgs e)
{
Stream myStream;
OpenFileDialog openFileDialog1 = new OpenFileDialog();
if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
if ((myStream = openFileDialog1.OpenFile()) != null)
{
string strfilename = openFileDialog1.FileName;
string filetext = File.ReadAllText(strfilename);
richTextBox1.Text = filetext;
textBox1.Text = openFileDialog1.FileName;
richTextBox1.LoadFile(#"C:\Users\Administrator\Documents\School\C#\DEEL 2\HW5\5.3 opdracht1\Sonnet 14.txt", RichTextBoxStreamType.PlainText);
}
}
}
private void button2_Click(object sender, EventArgs e)
{
}
If you want to use LINQ, you can do it pretty easily. Simply split the text on whitespaces, and then filter the array for words matching what you want. Here's a sample:
string search = "Me";
int count = richTextBox1.Text.Split(' ').Where(word => word == search).Count();
Separete all the words and after that you can do whatever you want
//Variable to store your count
int n = 0;
string stringToCompare = "Me";
string[] data = richTextBox1.Text.Split(' ');
for(int i=0;i<data.Length;i++)
{
if(data[i]==stringToCompare )
n++;
}
Console.WriteLine($"Word {stringToCompare } has appeared {n} times");
If you dont want case sensitive try something like
if(data[i].ToUpper() == stringToCompare.ToUpper() )
n++;
I am using Windows Form Application, in the application, there is two rich Textbox and one Button, I want the RichTextbox 2 to display RichTextbox 1 after using the Dictionary.How to do that?What is the code for the Button?
public Form1()
{
InitializeComponent();
Dictionary<char, string> dictionary = new Dictionary<char, string>();
dictionary.Add('a', "%");
dictionary.Add('A'," %");
dictionary.Add('b', " &");
dictionary.Add('B', " &");
dictionary.Add('c', " <");
dictionary.Add('C', " <");
}
private void button_Click(object sender, EventArgs e)
{
second_richtextbox= (???)
}
So that when I type cab it will translate to "<%&"
I want to translate the letter to different symbol.
Here's one way you could do it, using LINQ:
private void button_Click(object sender, EventArgs e)
{
second_richtextbox.Text = string.Join("",
first_richtextbox.Text
.Select(ch =>
dictionary.ContainsKey(ch) ? dictionary[ch] : ch.ToString()));
}
Or a more straightforward way using a loop and StringBuilder (I'd probably do it this way):
var result = new StringBuilder();
for (int i = 0; i < first_richtextbox.Text.Length; i++)
{
if (dictionary.ContainsKey(text[i]))
{
result.Append(dictionary[text[i]]);
}
else
{
result.Append(text[i]);
}
}
second_richtextbox.Text = result.ToString();
Try this code on your Click Event of Button
string frstvalue = richTextBox1.Text;
string finalvalue = "";
char[] a = richTextBox1.Text.ToArray();
foreach (char c in a)
{
if (dictionary.ContainsKey(c))
{
string value = dictionary[c];
finalvalue += value;
}
}
richTextBox2.Text = finalvalue;
I hope it will help
I have a problem when I try to display the list into the textbox. It only displays the last line from the list.txt file. I think for each new line it overwrites the first line from the textbox all the time ? thus showing only the last line from the file ?
what is it I need to think of to get it right ?
private void Form1_Load(object sender, EventArgs e)
{
const string f = "list.txt";
List<string> myList = new List<string>();
using (StreamReader r = new StreamReader(f))
{
string line;
while ((line = r.ReadLine()) != null)
{
myList.Add(line);
}
}
foreach (string s in myList)
{
textBox1.Text = string.Join(Environment.NewLine, s);
}
}
Instead of this:
foreach (string s in myList)
{
textBox1.Text = string.Join(Environment.NewLine, s);
}
Try:
textBox1.Text = string.Join(Environment.NewLine, myList);
And also make sure multiline property of textbox1 is set to true.
Because every time, you assign directly to the Text property which will remove the previous one . Here is the fix . Make Multiline of textbox true.
private void Form1_Load(object sender, EventArgs e)
{
const string f = "list.txt";
List<string> myList = new List<string>();
using (StreamReader r = new StreamReader(f))
{
string line;
while ((line = r.ReadLine()) != null)
{
myList.Add(line);
}
}
var listString = new StringBuilder()
foreach (string s in myList)
{
listString.Append(Environment.Newline)
listString.Append(s);
}
textBox1.Text = listString.ToString();
}
Based on my comment you can do this in one simple line by eliminating the foreach loop
textBox1.Text = string.Join(Environment.NewLine, myList.ToArray());
or just use the myList works the same
textBox1.Text = string.Join(Environment.NewLine, myList);
I have a WindowsForm that has a DataGridView that shows output of my app. The class with the button is DriveRecursion_Results.cs. I want it so that once the button is pushed by the user, my method FileCleanUp() in my SanitizeFileNames class is called. I'm not quite sure how to do this though.
Here is the code for both classes:
public partial class DriveRecursion_Results : Form
{
public DriveRecursion_Results()
{
InitializeComponent();
}
private void listView1_SelectedIndexChanged(object sender, EventArgs e)
{
}
public void DriveRecursion(string retPath)
{
//recurse through files. Let user press 'ok' to move onto next step
// string[] files = Directory.GetFiles(retPath, "*.*", SearchOption.AllDirectories);
string pattern = " *[\\~#%&*{}/<>?|\"-]+ *";
//string replacement = "";
Regex regEx = new Regex(pattern);
string[] fileDrive = Directory.GetFiles(retPath, "*.*", SearchOption.AllDirectories);
List<string> filePath = new List<string>();
dataGridView1.Rows.Clear();
try
{
foreach (string fileNames in fileDrive)
{
if (regEx.IsMatch(fileNames))
{
string fileNameOnly = Path.GetFileName(fileNames);
string pathOnly = Path.GetDirectoryName(fileNames);
DataGridViewRow dgr = new DataGridViewRow();
filePath.Add(fileNames);
dgr.CreateCells(dataGridView1);
dgr.Cells[0].Value = pathOnly;
dgr.Cells[1].Value = fileNameOnly;
dataGridView1.Rows.Add(dgr);
filePath.Add(fileNames);
}
else
{
DataGridViewRow dgr2 = new DataGridViewRow();
dgr2.Cells[0].Value = "No Files To Clean Up";
dgr2.Cells[1].Value = "";
}
}
}
catch (Exception e)
{
StreamWriter sw = new StreamWriter(retPath + "ErrorLog.txt");
sw.Write(e);
}
}
private void button1_Click(object sender, EventArgs e)
{
//i want to call SanitizeFileName's method FileCleanup here.
}
}
Here is SanitizeFileNames:
public class SanitizeFileNames
{
public void FileCleanup(List<string>filePath)
{
string regPattern = "*[\\~#%&*{}/<>?|\"-]+*";
string replacement = "";
Regex regExPattern = new Regex(regPattern);
foreach (string files2 in filePath)
{
try
{
string filenameOnly = Path.GetFileName(files2);
string pathOnly = Path.GetDirectoryName(files2);
string sanitizedFileName = regExPattern.Replace(filenameOnly, replacement);
string sanitized = Path.Combine(pathOnly, sanitizedFileName);
//write to streamwriter
System.IO.File.Move(files2, sanitized);
}
catch (Exception ex)
{
//write to streamwriter
}
}
}
}
private void button1_Click(object sender, EventArgs e)
{
List<string> paths = new List<string>()
// initialize paths to whatever is neccessary
//....
new SanitizeFileNames().FileCleanUp(paths)
}
Just create an instance of the class, and call the method.
However, the method itself does not use the state of the class, so it can be changed to a static method
public static void FileCleanup(List<string>filePath)
and you'll be able to call it without creating an instance, directly from the class, like this:
SanitizeFileNames.FileCleanUp(paths)