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++;
Related
private void ListBox_SelectedIndexChanged(object sender, EventArgs e)
{
{
string stringToSplit = ListBox.SelectedIndex;
string[] splitString;
splitString = stringToSplit.Split(new char[] { ',' });
textBoxName.Text = ListBox.SelectedItem.ToString();
}
Want to view the selected item in two textboxes.
To get the value of a selected item as a string from ListBox you can use the SelectedItem property instead of SelectedIndex.
Also, when you have the only single separator, then you don't need an array of chars. you can use the first overload of the split function.
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
string stringToSplit = listBox1.SelectedItem.ToString();
var splitString = stringToSplit.Split(',');
textBox1.Text = splitString[0];
textBox2.Text = splitString.Length > 1 ? splitString[1] : string.Empty;
}
I think you are looking for this. This will split words using , as the separating character.
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
string[] splitString;
string stringToSplit = listBox1.Items[listBox1.SelectedIndex].ToString();
splitString = listBox1.Items[listBox1.SelectedIndex].ToString().Split(',');
textBox2.Text = splitString[0];
if (splitString.Length>1) {
textBox3.Text = splitString[1];
}
else
{
textBox3.Text = "";
}
}
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:
I have set up a program that so far can browse for the location of a file that possesses data in a text file holding the locations of other files which then shows me if they exist, are missing or are a duplicate inside listboxes. The next step is to enable the user to select files in the checked list boxes and being given the option to either move or copy. I have already made buttons which allow this but I want to be able to use them for the checked boxes I the list boxes.(p.s) please ignore any comments I have made in the code they are just previous attempts of doing other things in the code.
My code so far:
namespace File_existence
{
public partial class fileForm : Form
{
private string _filelistlocation;
public fileForm()
{
InitializeComponent();
}
private void checkedListBox1_SelectedIndexChanged(object sender, EventArgs e)
{
}
public void fileForm_Load(object sender, System.EventArgs e)
{
_filelistlocation = textBox1.Text;
}
private void button1_Click(object sender, System.EventArgs e)
{
//GetDuplicates();
checkedListBox1.Items.Clear();
listBox2.Items.Clear();
ReadFromList();
}
private void GetDuplicates()
{
DirectoryInfo directoryToCheck = new DirectoryInfo(#"C:\\temp");
FileInfo[] files = directoryToCheck.GetFiles("*.*", SearchOption.AllDirectories);
var duplicates = files.GroupBy(x => x.Name)
.Where(group => group.Count() > 1)
.Select(group => group.Key);
if (duplicates.Count() > 0)
{
MessageBox.Show("The file exists");
FileStream s2 = new FileStream(_filelistlocation, FileMode.Open, FileAccess.Read, FileShare.Read);
// open _filelistlocation
// foreach line in _filelistlocation
// concatenate pat hand filename
//
}
}
public void ReadFromList()
{
int lineCounter = 0;
int badlineCounter = 0;
using (StreamReader sr = new StreamReader(_filelistlocation))
{
String line;
while ((line = sr.ReadLine()) != null)
{
string[] values = line.Split('\t');
if (values.Length == 2)
{
string fullpath = string.Concat(values[1], "\\", values[0]);
if (File.Exists(fullpath))
checkedListBox1.Items.Add(fullpath);
else
listBox2.Items.Add(fullpath);
++lineCounter;
}
else
++badlineCounter;
//Console.WriteLine(line);
}
}
}
//StreamReader files= new StreamReader(File)();
private void listBox1_SelectedIndexChanged(object sender, System.EventArgs e)
{
}
private void button2_Click(object sender, System.EventArgs e)
{
FolderBrowserDialog folderBrowserDlg = new FolderBrowserDialog();
folderBrowserDlg.ShowNewFolderButton = true;
DialogResult dlgResult = folderBrowserDlg.ShowDialog();
if (dlgResult.Equals(DialogResult.OK))
{
textBox1.Text = folderBrowserDlg.SelectedPath;
Environment.SpecialFolder rootFolder = folderBrowserDlg.RootFolder;
}
try
{
string fileName = "filetest1.txt";
string sourcePath = #"C:\Temp\Trade files\removed";
string targetPath = #"C:\Temp\Trade files\queued";
string sourceFile = System.IO.Path.Combine(sourcePath, fileName);
string destFile = System.IO.Path.Combine(targetPath,fileName);
System.IO.File.Copy(sourceFile, destFile, true);
}
catch (IOException exc)
{
MessageBox.Show(exc.Message);
}
}
private void button3_Click(object sender, System.EventArgs e)
{
try
{
string sourceFile = #"C:\Temp\Trade Files\queued\filetest1.txt";
string destinationFile = #"C:\Temp\Trade Files\processed\filetest1.txt";
System.IO.File.Move(sourceFile, destinationFile);
}
catch(IOException ex){
MessageBox.Show(ex.Message);//"File not found"
}
}
private void button4_Click(object sender, System.EventArgs e)
{
OpenFileDialog fileBrowserDlg = new OpenFileDialog();
//folderBrowserDlg.ShowNewFolderButton = true;
//folderBrowserDlg.SelectedPath = _filelistlocation;
fileBrowserDlg.FileName = textBox1.Text;
DialogResult dlgResult = fileBrowserDlg.ShowDialog();
if (dlgResult.Equals(DialogResult.OK))
{
textBox1.Text = fileBrowserDlg.FileName;
File_existence.Properties.Settings.Default.Save();
// Environment.SpecialFolder rootFolder = folderBrowserDlg.RootFolder;
}
}
private void button5_Click(object sender, System.EventArgs e)
{
if (!textBox1.Text.Equals(String.Empty))
{
if (System.IO.Directory.GetFiles(textBox1.Text).Length > 0)
{
foreach (string file in System.IO.Directory.GetFiles(textBox1.Text))
{
checkedListBox1.Items.Add(file);
}
}
else
{
checkedListBox1.Items.Add(String.Format("No file found: {0}", textBox1.Text));
}
}
}
}
}
The task I need to do is that the files that appear in the checked list box need to usually be moved or copied to another directory. That is fine as I can already do that with what I have coded, but what it does is it will move or copy all of the files in the checked list box. What I want to do is enable the user to only be able to select which files they what to move or copy through checking the checked list box so that only those files will be moved or copied.
EDIT: Could it be checkedListBox.checked items?
I am trying to open any selected textfile and have the text input be sent to a listbox... Originally I wrote this code for a textbox which worked great now that I am converting it to a listbox it doesnt seem to work so much. I left the default item names in order for better understanding of what is going on.
private void button1_Click(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
label1.Text = openFileDialog1.FileName;
listBox1.Items.Add = File.ReadAllText(label1.Text);
}
}
listBox1.Items.AddRange(File.ReadAllLines(label1.Text));
Try this :
listBox1.Items.AddRange(File.ReadLines(label1.Text).ToArray());
.Add() is a method and you are treating it like a property.
Try this code instead:
listBox1.Items.Add(File.ReadAllText(label1.text));
string[] lines = File.ReadLines("SomeFile.txt").ToArray();
foreach (var line in lines)
{
listBox1.Items.Add(line);
}
private void button1_Click(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
label1.Text = openFileDialog1.FileName;
//till here the same
//open filestream
System.IO.StreamReader file = new System.IO.StreamReader(openFileDialog1.FileName);
//loop trough lines
while ((line = file.ReadLine()) != null)
{
//add line to listbox
listBox1.Items.Add ( line);
}
}
}
Hi can i know why this code not working, it's working but it will also remove non duplicates entry and for some lists it will throw some error
ex:
This list working but it will also remove http://test1.com
http://test.com
http://test.com
http://test1.com
http://1test.com
And with this lists will throw this "System.ArgumentNullException was unhandled" error
http://test.com
http://test.com
http://test1.com
http://1test.com
http://etest.com
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog buka = new OpenFileDialog();
buka.InitialDirectory = "";
buka.Filter = "Text files(*.txt)|*.txt|All files (*.*)|*.*";
buka.FilterIndex = 2;
buka.RestoreDirectory = true;
buka.Title = "Cari";
buka.ShowDialog();
string bukafile = buka.FileName;
if (!String.IsNullOrEmpty(bukafile))
{
StreamReader isiFile = File.OpenText(bukafile);
while (isiFile.Peek() != -1)
{
if (!listBox1.Items.Contains(isiFile.ReadLine()))
{
listBox1.Items.Add(isiFile.ReadLine());
}
}
isiFile.Close();
}
}
You should cache the line from isiFile.ReadLine() so you compare the same line as you're adding.
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog buka = new OpenFileDialog();
buka.InitialDirectory = "";
buka.Filter = "Text files(*.txt)|*.txt|All files (*.*)|*.*";
buka.FilterIndex = 2;
buka.RestoreDirectory = true;
buka.Title = "Cari";
buka.ShowDialog();
string bukafile = buka.FileName;
if (!String.IsNullOrEmpty(bukafile))
{
StreamReader isiFile = File.OpenText(bukafile);
while (isiFile.Peek() != -1)
{
// use local variable here
string line = isiFile.ReadLine();
if (!listBox1.Items.Contains(line))
{
listBox1.Items.Add(line);
}
}
isiFile.Close();
}
}
If you don't have a very huge file you could replace a lot of your code using
var lines = File.ReadLines(bukafile).Distinct();
listBox1.DataSource = lines.ToList();
You're reading two lines, one for each ReadLine() call. You use the first line to do the .Contains check, and the second line to add to the listbox. These two lines aren't related to each other in any way.
So for the first list, you first check if http://test.com, the first line, is in the listbox. It isn't, so you read the next line, coincidentally also http://test.com, and add that to the listbox. Then, you check if http://test1.com is in the listbox, find that it isn't, and then proceed to add http://1test.com to the listbox.
For the second list, you have an odd number of entries, so the final call to ReadLine returns, I'm guessing, null, which you can't add to the listbox.
The fix is
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog buka = new OpenFileDialog();
buka.InitialDirectory = "";
buka.Filter = "Text files(*.txt)|*.txt|All files (*.*)|*.*";
buka.FilterIndex = 2;
buka.RestoreDirectory = true;
buka.Title = "Cari";
buka.ShowDialog();
string bukafile = buka.FileName;
if (!String.IsNullOrEmpty(bukafile))
{
StreamReader isiFile = File.OpenText(bukafile);
while (isiFile.Peek() != -1)
{
string line = isiFile.ReadLine();
if (!listBox1.Items.Contains(line))
{
listBox1.Items.Add(line);
}
}
isiFile.Close();
}
}