Here is some code i put together to search for numbers in a text file. It work's great for what i'm trying to do. right now it finds 7 locations and i need to read the lines at the 7 different indexes. what might be the best way to start this. Thanks, this is in C#.
private void button1_Click(object sender, EventArgs e)
{
richTextBox1.Text = "";
using (OpenFileDialog dlgOpen = new OpenFileDialog())
{
//long count = 0; string line;
//bool start = false;
//string line;
List<String> LinesFound = new List<string>();
// Available file extensions
dlgOpen.Filter = "All files(*.*)|*.*";
// Initial directory
dlgOpen.InitialDirectory = "C://bin";
// OpenFileDialog title
dlgOpen.Title = "Load";
// Show OpenFileDialog box
if (dlgOpen.ShowDialog() == DialogResult.OK)
textBox1.Text = dlgOpen.FileName;
{
string str = System.IO.File.ReadAllText(dlgOpen.FileName);
Regex reg = new Regex("333333");
Match sat = reg.Match(str);
while (sat.Success)
{
richTextBox1.Text += (sat.Index + " "); //shows index where 333333 is
sat = reg.Match(str, sat.Index + sat.Length);
{
{
}
}
}
}
}
}
You can use ReadAllLines instead of ReadAllText, and match each line one by one, use a int[] variable to store all your matching line index.
var lines = File.ReadAllLines(AppDomain.CurrentDomain.BaseDirectory + "/files/file.txt");
Regex reg = new Regex("333333");
string str;
for(int i =1; i<lines.Length;i++)
{
str = lines[i];
Match sat = reg.Match(str);
if (sat.Success)
{
richTextBox1.Text += (i + 1 +" "); //shows index where 333333 is
}
}
Related
I would like to store line by line from the text file after read it. However, the text that store into the temporary list must be after the ": ".
Below is the example of content in my text file:
Name: Johny
Age: 18
Favourite: Basketball, Food
I would like to store Johny as list[0], 18 as list[1], and etc.
For the Favourite, it should be store separately such as Basketball as list[2] and Food as list[3] and etc. This is because I need to place it back to different textBox afterward.
Below is my example code:
private void storeDataList()
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.DefaultExt = ".txt";
ofd.Filter = "Text Document (*.txt) | *.txt";
string filename = ofd.FileName;
string line = "";
if (ofd.ShowDialog() == true)
{
StreamReader sr = new StreamReader(ofd.FileName);
while (line != null)
{
for (int i = 0; i < 10; i++)
{
List<string> elements = new List<string>();
string readText = File.ReadAllText(filename);
i = readText.LastIndexOf(": ");
elements.Add[i];
}
}
sr.Close();
detailsTextBox.Text = File.ReadAllText(filename);
}
}
Here's a one liner with LINQ that reads the file into lines, split the lines on : and takes what's after, then splits that on , for further granularity:
var output = File.ReadAllLines(filename).SelectMany(l => l.Split(':')[1].Split(',').Select(s => s.Trim());
Which outputs a list of: Johny, 18, Basketball, Food.
You can:
read it line by line
separate the fields and it's valued by splitting it with : delimiter
check the line every three-line
split the favorite value by comma delimiter ,
clean the value with trim to remove whitespaces
private void storeDataList()
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.DefaultExt = ".txt";
ofd.Filter = "Text Document (*.txt) | *.txt";
string filename = ofd.FileName;
string line = "";
if (ofd.ShowDialog() == true)
{
List<string> elements = new List<string>();
using (var reader = new StreamReader(ofd.FileName))
{
int rowNumber = 1;
//Dynamically stop the loop until the end of the stream
while (!reader.EndOfStream)
{
//Split to separate field name and values
var textLine = reader.ReadLine().Split(':');
//Since favorite fields are in multiples of three, we re-split the value by comma every three line
if (rowNumber % 3 == 0)
{
var favouriteArr = textLine[1].Split(',');
for (int i = 0; i < favouriteArr.Length; i++)
{
//trim to clean whitespace
elements.Add(favouriteArr[i].Trim());
}
}
else
{
elements.Add(textLine[1].Trim());
}
rowNumber++;
}
}
// # just a new delimiter to print the elements in a text box
detailsTextBox.Text = string.Join('#', elements);
}
}
Data was passed from another form which containing a user entry, using Streamreader find the specific user entry in the text file and display the 5th component in the array.
in the login form, I passed the user entry: seow into this form, how do I make sure it displays 20, in label3?
in account.txt
seow 1111 wen 12345 20 50
user 1234 user1 12345 70 80
C# Code:
List<string> user = new List<string>();
private void Balance_Load(object sender, EventArgs e)
{
string username;
username = login.accountname;
StreamReader sr = new StreamReader("account.txt");
string line = "";
if (user.Contains(username))
{
while ((line = sr.ReadLine()) != null)
{
string[] components = line.Split(" ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
label3.Text = string.Join(" ", components[5]);
}
sr.Close();
}
}
here is an example of I have tried
string path1 = AppDomainAppPath + "\\Subscribtion\\Subscribe.txt";
System.IO.StreamReader file = new System.IO.StreamReader(path1);
var lines = File.ReadAllLines(path1);
for (var i = 0; i < lines.Length; i += 1)
{
// Process line
txtcollege.Value = lines[1];
txtplace.Value = lines[3];
}
file.Close();
ouput
ive madeit by changing the condition, thanks for the ideas
while ((line = sr.ReadLine()) != null)
{
string[] components = line.Split(" ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
if( components.Contains(username))
{
curbal = string.Join(" ", components[5]);
label3.Text = curbal;
savbal = string.Join(" ", components[6]);
label5.Text = savbal;
}
}
sr.Close();
I want the user to be able to chose a text file written in a certain way (1 number per line) and then have the file converted into an array. I have bits and pieces of it working but I cant get it to all work at the same time. Any help would be appreciated.
private void Load_Button_Click(object sender, EventArgs e)
{
int counter = 0;
string line;
List<int> list = new List<int>();
string fileName = "";
//OpenFileDialog ofd = new OpenFileDialog();
//ofd.Filter = "TXT File|*.txt";
//ofd.Title = "Open File";
// if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
// {
File_Label.Text = "C:/Users/Neilan/Desktop/sample.txt";
//fileName = "#" + ofd.SafeFileName;
//MessageBox.Show(ofd.FileName);
System.IO.StreamReader file = new System.IO.StreamReader(#"C:\Users\Neilan\Desktop\sample.txt");
while ((line = file.ReadLine()) != null)
{
Unsorted_Box.Text += line + ", ";
//list.Add(int.Parse(fileName));
counter++;
}
dataArray = list.ToArray();
// }
}
You can do this.
var numberarray = File.ReadAllLines("stringpath").Select(int.Parse).ToArray();
Looking at your code, I guess you want to show these values in comma separated format to user. You can achieve this with following code snippet.
Unsorted_Box.Text = String.Join(",", numberarray.ToArray());
Hope this helps !
This problem can be solved by one line
var resultArray = Array.ConvertAll(System.IO.File.ReadAllLines("filename.type"), str => int.Parse(str));
Instead of "filename.type" you can put something like File_Label.Text
When I open a file (I made myself) I need to use somethings out of the string of text that comes trough. I want to use some parts of the text as coordinates to draw a graph with.
private void openToolStripMenuItem_Click(object sender, EventArgs e)
{
char XgetalEen;
char XgetalTwee;
char YgetalEen;
char Ygetaltwee;
string XgetalSamen = "";
string YgetalSamen = "";
int coordinaatX;
int coordinaatY;
DialogResult lel = MessageBox.Show("Do you want to close this file?", "OPEN", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (lel == DialogResult.Yes)
{
Open();
foreach(string s in Gcowde)
{
XgetalEen = s[5];
XgetalTwee = s[6];
YgetalEen = s[8];
Ygetaltwee = s[9];
XgetalSamen += XgetalEen + XgetalTwee;
YgetalSamen += YgetalEen + Ygetaltwee;
if(XgetalTwee==' ')
{
XgetalSamen = "";
XgetalTwee = '0';
XgetalSamen += XgetalTwee + XgetalEen;
YgetalEen = s[7];
Ygetaltwee = s[8];
YgetalSamen = "";
YgetalSamen += YgetalEen + Ygetaltwee;
}
if(Ygetaltwee==' ')
{
Ygetaltwee = '0';
YgetalSamen = "";
YgetalSamen += Ygetaltwee + YgetalEen;
}
MessageBox.Show(XgetalSamen + " " + YgetalSamen);
Int32.TryParse(XgetalSamen, out coordinaatX);
Int32.TryParse(YgetalSamen, out coordinaatY);
currentLocation.X += coordinaatX;
currentLocation.Y += coordinaatY;
Coord.Add(new Point(currentLocation.X, currentLocation.Y));
}
drawerryting();
}
}
public void Open()
{
Gcowde.Clear();
listBox1.Items.Clear();
Coord.Clear();
werkVlak.Clear(Color.Black);
Coord.Add(new Point(pictureBox1.Width / 2, pictureBox1.Height / 2));
drawerryting();
OpenFileDialog openFileDialog1 = new OpenFileDialog();
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
StreamReader sr = new StreamReader(openFileDialog1.FileName);
string errything = sr.ReadToEnd();
string charAdded = "";
foreach (char s in errything)
{
if (s == '\n')
{
Gcowde.Add(charAdded);
charAdded = "";
}
else
{
charAdded += s;
}
}
foreach (string s in Gcowde)
{
listBox1.Items.Add(s);
}
sr.Close();
}
This is the code how I open the file and get the coordinates out of the string. The string is of this kind L1 G2 X50 Y50. i need to get the 2 50s out of the string.
ps.: the variables are in dutch.
XgetalEen = XnumberOne, XgetalTwee=XnumberTwo,
same goes for Y.
XgetalSamen=XnumberTogether, YgetalSamen=YnumberTogether.
This is a simple example how you could parse the file:
// Read your file using File.ReadAllLines
String[] lines = new[] { "L1 G2 X50 Y50", "L1 G2 X50 Y50" };
foreach (var line in lines)
{
String[] values = line.Split(' ');
string x = values.Where(s => s.StartsWith("X")).First().Replace("X", String.Empty);
int xCoordinate = Convert.ToInt32(x);
}
Don't forget to add all necessary checks and reading of other variables.
how to recognize new line c# while uploading word documents..? i have to give next line as a new word in word document here what is happening means if i add three or more words in .doc in separate line its taking as one word i want to separate the words but if i give a space after a word it is taking as expected without giving space if i start a new word in new line its taking as one word
money
power
cash
moneypowercash
like this iam getting here if i give space after these words its getting as expected
how to resolve this issue here i will give my code to generating this keyword
protected void btnSubmit_Click(object sender, EventArgs e)
{
try
{
if (cmbDepartment.SelectedValue != "0" && cmbDocumentType.SelectedValue != "0")
{
TodayDate = DateTime.Today.ToString("yyyy-MM-dd");
TempFolder = System.Configuration.ConfigurationManager.AppSettings["TempWorkFolder"];
TextReader reader = new FilterReader(TempFolder + Session["EncyptImgName"]);
StringBuilder Keywords = new StringBuilder();
using (reader)
{
Keywords = Keywords.Append(reader.ReadToEnd());
}
//remove common words
string[] removablewords = { ":", ".", "~"};
foreach (string st in removablewords)
{
Keywords.Replace(st, " ");
}
//Reomve unwated spaces
while (Keywords.ToString().Contains(" "))
{
Keywords.Replace(" ", " ");
}
string str = Keywords.ToString();
Keywords.Clear();
Keywords.Append("<words><s>" + str.Replace(" ", "</s><s>") + "</s></words>");
string xml = Keywords.ToString();
XElement items = XElement.Parse(xml);
var groups = from t in items.Descendants("s")
group t by t.Value.ToLower() into g
select new KeyFrequency(g.Key, g.Count());
groups = groups.OrderByDescending(g => g.Frequency).Take(15);
keyvalues = new List<string>();
foreach (KeyFrequency g in groups)
{
keyvalues.Add(g.Key);
}
for (key = 0; key < keyvalues.Count && key < 10; key++)
{
Button btn = (Button)pnlKeywords.FindControl("Button" + Convert.ToString(key + 1));
btn.Visible = true;
btn.Text = keyvalues[key];
btn.CommandArgument = keyvalues[key];
}
if (key < 10)
{
for (key = key; key < 10; key++)
{
Button btn = (Button)pnlKeywords.FindControl("Button" + Convert.ToString(key + 1));
btn.Visible = false;
}
}
else
{
AsyncFileUpload1.BackColor = System.Drawing.Color.Red;
}
}
}
catch (Exception ex)
{
Button1.Text = "Keywords Not Available for This Document";
Button1.CommandArgument = null;
Button2.Visible = false;
Button3.Visible = false;
Button4.Visible = false;
Button5.Visible = false;
Button6.Visible = false;
Button7.Visible = false;
Button8.Visible = false;
Button9.Visible = false;
Button10.Visible = false;
}
}
For each new line, try replacing \n with "</w:t><w:br/><w:t>". It worked for me.
string.Replace("\n", "</w:t><w:br/><w:t>")