SaveFileDialog sfd = new SaveFileDialog();
sfd.Filter = "Text File|*.txt";
sfd.Title = "Save Text File";
if (sfd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
string path = sfd.FileName;
string left = string.Format(EmailTxtbx.Text, Environment.NewLine);
string right = string.Format(PasslTxtbx.Text, Environment.NewLine);
string[] leftSplit = left.Split(new[] { Environment.NewLine }, StringSplitOptions.None);
string[] rightSplit = right.Split(new[] { Environment.NewLine }, StringSplitOptions.None);
string output = "";
if (leftSplit.Length == rightSplit.Length)
{
for (int i = 0; i < leftSplit.Length; i++)
{
output += leftSplit[i] + ":" + rightSplit[i] + Environment.NewLine;
}
}
using (StreamWriter bw = new StreamWriter(File.Create(path)))
{
textBox1.Text = output;
bw.Write(output);
bw.Close();
}
}
Hey. I Have an issue. Lets Say I have 2 Textboxes I want The Textboxes
Be Together:
TextBox1:
Test41
Test414
Test41
TextBox2:
Test55
Test56
Test54
TextBox3:
Test41:Test55
Test414:Test56
Test41:Test54
I want to load 2 files one to the first textbox and for the second textbox and combine With delimiter like ":" I Tried This Code And Its Not working. I'm new on c#.
Hope Someone Can Help Me
I’ll start from scratch. I have 2 textbox. In the first textbok it’s the mails. In the second textbox it’s passwords. What I need to do to combine the textboxes with “:”
Try this code snippet:
var txt1 = textBox1.Lines.Where(a => !string.IsNullOrEmpty(a)).ToArray();
var txt2 = textBox2.Lines.Where(b => !string.IsNullOrEmpty(b)).ToArray();
var txt3 = "";
for(int i = 0; i < txt1.Length; i++)
{
if (i < txt2.Length)
txt3 += $"{txt1[i]}:{txt2[2]}{Environment.NewLine}";
else
txt3 += $"{txt1[i]}{Environment.NewLine}";
}
textBox3.Text = txt3;
Good luck.
Related
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 am trying to save the selected items from the Type to a text file(checklistbox).
I also am saving the main actors(treeview) to a text file
This part works, and they are saving.
However when I try to open the text file to repopulate the data back into the form, I am getting the error:
Index was outside the bounds of the array.
Below is my code for the save and open functions:
private void openDatabaseToolStripMenuItem_Click(object sender, EventArgs e)
{
// Open the file and upload the information
openFileDialog1.ShowDialog();
Stream s1 = openFileDialog1.OpenFile();
StreamReader reader = new StreamReader(s1);
saveDatabaseToolStripMenuItem.Enabled = true;
string infomovie = reader.ReadLine();
string[] select = infomovie.Split('#');
int nline = select.Length;
txtTitle.Text = select[0];
txtYear.Text = select[1];
txtDir.Text = select[2];
txtDur.Text = select[3];
int nactors = Convert.ToInt32(select[4]);
// put the number of actors in the file
for (int i = 0; i < nactors; i++)
{
tvActor.Nodes.Add(select[4 + i]);
}//end of for loop
int genre = Convert.ToInt32(select[5]);
// put the number of actors in the file
for (int i = 0; i < genre; i++)
{
cBoxType.Items.Add(select[5 + i]);
}//end of for loop
reader.Close();
}
private void saveDatabaseToolStripMenuItem_Click(object sender, EventArgs e)
{
//save data enter into form to text file
saveFileDialog1.ShowDialog();
Stream textOut = saveFileDialog1.OpenFile();
StreamWriter writer = new StreamWriter(textOut);
//creates string called infomovie
String infomovie = "";
//prints parameters
infomovie += txtTitle.Text + "#";
infomovie += txtYear.Text + "#";
infomovie += txtDir.Text + "#";
infomovie += txtDur.Text + "#";
//gets values from check list box
int genre = cBoxType.Items.Count;
infomovie += genre.ToString() + "#";
//gets values for tree view
int nactors = tvActor.Nodes.Count;
infomovie += nactors.ToString() + "#";
for (int i = 0; i < nactors; i++)
{
//convert treeview to string
infomovie += tvActor.Nodes[i].Text + ",";
}
//sep
infomovie += "#";
for (int i = 0; i < genre; i++)
{
if (cBoxType.GetItemCheckState(i) == CheckState.Checked)
{
//if statement to check which boxes are selected then converts to string
infomovie += cBoxType.Items[i].ToString() + ",";
}
}
//sep
infomovie += "#";
writer.WriteLine(infomovie);
writer.Close();
}
your actor count stored at index 5 and genre count is at 4 and Actorlist at 6 and which is separated by , so you've to get element at index 6 and then split them by , and do loop over it and add it to tvActor.Nodes
string[] actorlist= select[6].Split(',');
// Then Do loop here
Same goes for GenreList..
currently have the following code:
string[] fileLineString = File.ReadAllLines(Server.MapPath("~") + "/App_Data/Users.txt");
for (int i = 0; i < fileLineString.Length; i++)
{
string[] userPasswordPair = fileLineString[i].Split(' ');
if (Session["user"].ToString() == userPasswordPair[0])
{
userPasswordPair[i].Replace(userPasswordPair[1], newPasswordTextBox.Text);
}
}
}
the text file is set out as: 'username' 'password
what i'm trying to do is be able to edit the password and replace it with a new one using my code, but my code seems to do nothing and the text file just stays the same.
string[] fileLineString = File.ReadAllLines(Server.MapPath("~") + "/App_Data/Users.txt");
for (int i = 0; i < fileLineString.Length; i++)
{
string[] userPasswordPair = fileLineString[i].Split(' ');
if (Session["user"].ToString() == userPasswordPair[0])
{
// set the new password in the same list and save the file
fileLineString[i] = Session["user"].ToString() + " " + newPasswordTextBox.Text;
File.WriteAllLines((Server.MapPath("~") + "/App_Data/Users.txt"), fileLineString);
break; // exit from the for loop
}
}
At the moment, you're not storing the file.
Your replace is not assigned to a variable (Replace does not edit or write anything, it just returns the new string object).
Corrected code:
string[] fileLineString = File.ReadAllLines(Server.MapPath("~") + "/App_Data/Users.txt");
for (int i = 0; i < fileLineString.Length; i++)
{
string[] userPasswordPair = fileLineString[i].Split(' ');
if (Session["user"].ToString() == userPasswordPair[0])
{
fileLineString[i] = fileLineString[i].Replace(userPasswordPair[1], newPasswordTextBox.Text);
break;
}
}
File.WriteAllLines((Server.MapPath("~") + "/App_Data/Users.txt", fileLineString);
String _userName = "User";
String _newPassword = "Password";
// Reading All line from file
String _fileContent = System.IO.File.ReadAllLines("filePath").ToString();
// Pattern which user password like to changed
string _regPettern = String.Format(#"{0} ?(?<pwd>\w+)[\s\S]*?", _userName);
Regex _regex2 = new Regex(_regPettern, RegexOptions.IgnoreCase);
String _outPut = Regex.Replace(_fileContent, _regPettern, m => m.Groups[1] + " " + _newPassword);
// Writing to file file
System.IO.File.WriteAllText("filePath", _outPut);
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
}
}
I am creating a HTML to text parser. I need to remove all HTML elements and want to do a carriage return everytime there is a <BR> and then remove the <BR> as well after so there are no HTML tags left. I then want to parse the text for a certain string that is in the combobox. Thank you in advance for your help.
private void navigateWeb_Click(object sender, EventArgs e)
{
openFD.Title = "Select your configuration file";
openFD.InitialDirectory = "C:";
openFD.FileName = "";
openFD.Filter = "Config File (*.cfg)|*.cfg|Text File (*.txt)|*.txt|All Files (*.*)|*.*";
openFD.ShowDialog();
MyURL = openFD.FileName;
//Open and read file
System.IO.StreamReader objReader;
objReader = new System.IO.StreamReader(MyURL);
richTextBox1.Text = objReader.ReadToEnd();
var lines = File.ReadAllLines(MyURL)
.Select(l => l.Trim())
.Where(l => l.StartsWith(comboBox1.Text));
textBox1.Text = String.Join(Environment.NewLine, lines);
}
*********UPDATE*****
Here is the solution that got the job done:
public static string RemoveHTML(string text)
{
text = text.Replace(" ", " ").Replace("<br>", "\n");
var oRegEx = new System.Text.RegularExpressions.Regex("<[^>]+>");
return oRegEx.Replace(text, string.Empty);
}
private void navigateWeb_Click(object sender, EventArgs e)
{
openFD.Title = "Enter URL in the box below";
openFD.InitialDirectory = "C:";
openFD.FileName = "http://msnconf/configtc.aspx?IP=10.6.64.200&m=c";
openFD.Filter = "HTTP://|*.*|Config File (*.cfg)|*.cfg|Text File (*.txt)|*.txt|All Files (*.*)|*.*";
//openFD.ShowDialog();
if (openFD.ShowDialog() == DialogResult.Cancel)
{
//MessageBox.Show("cancel button clicked");
}
else
{
MyURL = openFD.FileName;
webBrowser1.Visible = true;
richTextBox1.Visible = false;
permitACL.Enabled = true;
//webBrowser1.Navigate(new Uri(MyURL.SelectedItem.ToString()));
webBrowser1.Navigate(MyURL);
//Open and read file
System.IO.StreamReader objReader;
objReader = new System.IO.StreamReader(MyURL);
richTextBox1.Text = objReader.ReadToEnd();
//Read all lines of file
// String lines = objReader.ReadToEnd();
String[] crString = { "<BR> " };
String[] aLines = richTextBox1.Text.Split(crString, StringSplitOptions.RemoveEmptyEntries);
// String[] lines = File.ReadAllLines(MyURL);
String noHtml = String.Empty;
for (int x = 0; x < aLines.Length; x++)
{
if(permitACL.Checked)
{
if (aLines[x].Contains("permit"))
{
noHtml += (RemoveHTML(aLines[x]) + "\r\n");
}
}
if (aLines[x].Contains(comboBox1.Text))
{
noHtml += (RemoveHTML(aLines[x]) + "\r\n");
}
}
//Find lines that match our text in the combobox
//lines.Select(l => l.Trim());
//.Where(l => l.StartsWith(comboBox1.Text));
//Print results to textbox
textBox1.Text = String.Join(Environment.NewLine, noHtml);
}
}
I suggest you use the HTML Agility Pack - it is an HTML parser that you can query with using XPath syntax.
public static string RemoveHTML(string text)
{
text = text.Replace(" ", " ").Replace("<br>", "\n");
var oRegEx = new System.Text.RegularExpressions.Regex("<[^>]+>");
return oRegEx.Replace(text, string.Empty);
}