I'm new for c#, and i need to write a programme with a button (clicking it to show a .txt file)
could someone give me some idea or may be an example code
thanks
Answer for WinForms:
Place textBox named tbBrowser and Button named bBrowse on form. Double-click button to create button Click handler. Place the following code in the handler:
String filename = #"C:\Temp\1.txt";
using (StreamReader rdr = new StreamReader(filename))
{
String content = rdr.ReadToEnd();
tbBrowser.Text = content;
}
See StreamReader documentation for reference.
Answer for ASP.NET would be completely different, but it's unlikely you are asking about that (at least word program in question makes me think so)
You haven't said if you wanted to use winforms, wpf or something else. Anyway, the code below will work for winforms - just add a textbox to your form:
private void button1_Click(object sender, EventArgs e)
{
// Create reader & open file
using (TextReader tr = new StreamReader(#"C:\myfile.txt"))
{
textBox1.Text += tr.ReadToEnd();
}
}
If you are creating windows form appln add a button to you form
double click the button
and in the method write the following code
private void button1_Click(object sender, EventArgs e)
{
string filePath = "give your path";
// or you can give your path in app.config and read from app.config if you want
// to change the path .
if (File.Exists(filePath))
{
StreamReader reader = new StreamReader(filePath);
do
{
string textLine = reader.ReadLine() + "\r\n";
}
while (reader.Peek() != -1);
reader.Close();
}
}
Related
I created simple example and I can't find solution anywhere. I want to save UI textbox data, and open it in another(same) windows form file.
Here is code example:
private void btnSave_Click(object sender, EventArgs e)
{
SaveFileDialog sfd = new SaveFileDialog();
if (sfd.ShowDialog() == DialogResult.OK)
{
StreamWriter write = new StreamWriter(File.Create(sfd.FileName));
write.Write(txtFirstInput.Text);
write.Write(txtSecondInput.Text);
write.Close();
write.Dispose();
}
}
private void btnOpen_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
if(ofd.ShowDialog() == DialogResult.OK)
{
StreamReader read = new StreamReader(File.OpenRead(ofd.FileName));
txtFirstInput.Text = read.ReadLine();
txtSecondInput.Text = read.ReadLine();
read.Close();
read.Dispose();
}
}
The problem I get here is that all inputed data get in first textbox. How to separate it? What is the easiest and most efficient way?
Should I create and use byte buffer (and HxD) for streaming through user input?
Can someone please give me some directions or examples.
Thank you for your time
You use ReadLine to read data back, so you need to use WriteLine when writing data to disk
private void btnSave_Click(object sender, EventArgs e)
{
SaveFileDialog sfd = new SaveFileDialog();
if (sfd.ShowDialog() == DialogResult.OK)
{
using(StreamWriter write = new StreamWriter(File.Create(sfd.FileName)))
{
write.WriteLine(txtFirstInput.Text);
write.WriteLine(txtSecondInput.Text);
}
}
}
Using Write, the data is written to disk without a line carriage return and so it is just on one single line. When you call ReadLine all the data is read and put on the first textbox.
Also notice that it is always recommended to enclose a IDisposable object like the StreamWriter inside a using statement. This approach will ensure that your Stream is correctly closed and disposed also in case of exceptions. (The same should be applied to the StreamReader below)
I have a winform app with the following functionality:
Has a multiline textbox that contain one URL on each line - about 30 URLs (each URL is different but the webpage is the same (just the domain is different);
I have another textbox in which I can write a command and a button that sends that command to an input field from the webpage.
I have a WebBrowser controller ( I would like to do all the things in one controller )
The webpage consist of a textbox and a button which I want to be clicked after I insert a command in that textbox.
My code so far:
//get path for the text file to import the URLs to my textbox to see them
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog fbd1 = new OpenFileDialog();
fbd1.Title = "Open Dictionary(only .txt)";
fbd1.Filter = "TXT files|*.txt";
fbd1.InitialDirectory = #"M:\";
if (fbd1.ShowDialog(this) == DialogResult.OK)
path = fbd1.FileName;
}
//import the content of .txt to my textbox
private void button2_Click(object sender, EventArgs e)
{
textBox1.Lines = File.ReadAllLines(path);
}
//click the button from webpage
private void button3_Click(object sender, EventArgs e)
{
this.webBrowser1.Document.GetElementById("_act").InvokeMember("click");
}
//parse the value of the textbox and press the button from the webpage
private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
newValue = textBox2.Text;
HtmlDocument doc = this.webBrowser1.Document;
doc.GetElementById("_cmd").SetAttribute("Value", newValue);
}
Now, how can I add all those 30 URLs from my textbox in the same webcontroller so that I can send the same command to all of the textboxes from all the webpages and then press the button for all of them ?
//EDIT 1
So, I have adapted #Setsu method and I've created the following:
public IEnumerable<string> GetUrlList()
{
string f = File.ReadAllText(path); ;
List<string> lines = new List<string>();
using (StreamReader r = new StreamReader(f))
{
string line;
while ((line = r.ReadLine()) != null)
lines.Add(line);
}
return lines;
}
Now, is this returning what it should return, in order to parse each URL ?
If you want to keep using just 1 WebBrowser control, you'd have to sequentially navigate to each URL. Note, however, that the Navigate method of the WebBrowser class is asynchronous, so you can't just naively call it in a loop. Your best bet is to implement an async/await pattern detailed in this answer here.
Alternatively, you CAN have 30 WebBrowser controls and have each one navigate on its own; this is roughly equivalent to having 30 tabs open in modern browsers. Since each WebBrowser is doing identical work, you can just have 1 DocumentCompleted event written to handle a single WebBrowser, and then hook up the others to the same event. Do note that the WebBrowser control has a bug that will cause it to gradually leak memory, and the only way to solve this is to restart the application. Thus, I would recommend going with the async/await solution.
UPDATE:
Here's a brief code sample of how to do the 30 WebBrowsers way (untested as I don't have access to VS right now):
List<WebBrowser> myBrowsers = new List<WebBrowser>();
public void btnDoWork(object sender, EventArgs e)
{
//This method starts navigation.
//It will call a helper function that gives us a list
//of URLs to work with, and naively create as many
//WebBrowsers as necessary to navigate all of them
IEnumerable<string> urlList = GetUrlList();
//note: be sure to sanitize the URLs in this method call
foreach (string url in urlList)
{
WebBrowser browser = new WebBrowser();
browser.DocumentCompleted += webBrowserDocumentCompleted;
browser.Navigate(url);
myBrowsers.Add(browser);
}
}
private void webBrowserDocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
//check that the full document is finished
if (e.Url.AbsolutePath != (sender as WebBrowser).Url.AbsolutePath)
return;
//get our browser reference
WebBrowser browser = sender as WebBrowser;
//get the string command from form TextBox
string command = textBox2.Text;
//enter the command string
browser.Document.GetElementById("_cmd").SetAttribute("Value", command);
//invoke click
browser.Document.GetElementById("_act").InvokeMember("click");
//detach the event handler from the browser
//note: necessary to stop endlessly setting strings and clicking buttons
browser.DocumentCompleted -= webBrowserDocumentCompleted;
//attach second DocumentCompleted event handler to destroy browser
browser.DocumentCompleted += webBrowserDestroyOnCompletion;
}
private void webBrowserDestroyOnCompletion(object sender, WebBrowserDocumentCompletedEventArgs e)
{
//check that the full document is finished
if (e.Url.AbsolutePath != (sender as WebBrowser).Url.AbsolutePath)
return;
//I just destroy the WebBrowser, but you might want to do something
//with the newly navigated page
WebBrowser browser = sender as WebBrowser;
browser.Dispose();
myBrowsers.Remove(browser);
}
I have a text file that is stored in my local disk.Now in my winform application i have a button.As per my requirement i have to read that text file line by line upon the click of the Button.For example ,On first button click it should read first line of the textfile and on second button click it should read second line and so on.
I know how to read a textfile line by line in c# but on every button click i am having problem.
Here is the code to read line by line ..
StreamReader sr=new StreamReader("C://");
string line=sr.ReadLine();
Please help me ..
Is there a reason it needs to be READ line by line? Could you not read the entire file into a list or array when your form is loaded then just iterate through a list of lines? You would just need to keep track of the current button click count and use that to get the line from a list / array.
public class TextReader : Form
{
string[] lines;
int currentIndex = 0;
public TextReader ()
{
InitializeComponent();
lines = File.ReadAllLines("C:\\myTextFile.txt");
}
public void Button_Click(object sender, EventArgs e)
{
TextBox1.Text = lines[currentIndex];
currentIndex++;
}
}
You probably want to keep the StreamReader open for the duration of your form's life.
public class mainForm : Form
{
public mainForm()
{
InitializeComponent();
m_lines = System.IO.File.ReadLines(path).GetEnumerator();
// alternatively, m_lines = System.IO.File.ReadAllLines(path).GetEnumerator();
// this would read it all at once, which would have the advantage of not locking up the file, but would take longer to load and would be harder on memory.
}
private IEnumerator<string> m_lines;
public void Button_Click(object sender, EventArgs e)
{
if (m_lines.MoveNext())
TextBox1.Text = m_lines.Current;
else
MessageBox.Show("End of file!");
}
}
So i am creating a simple program that keeps track of my notes from work. The code i have works fine but i was thinking today about a different way to make it work and still achieve the same end result.
Currently the user types everything into several textboxes and checks a few checkboxes they click the save button and all the information plus some predetermined formatting is put into a text file and then they click the copy button and the textfile is read and output to the notes_view textbox so they can ensure the notes are formatted properly and it also copies to the clipboard.
Now what i would like it to do is as the user is typing in each textbox it will output automatically to the notes_view textbox and also the same with the checkboxes(needs to keep the formatting and predetermined lines of text as well) and then the user can just push one button that will copy it to the clipboard without having to use the file to store the information.
I am hoping this would be as simple as my program currently is but just going a different way to get the same end result.
I am rather new to C# and programming in general so any ideas on how to do this and where i should begin please let me know. Also i do understand this will essentially require an entire rewrite of my code.
Here is the current complete code for my program as is.
public partial class notes_form : Form
{
public notes_form()
{
InitializeComponent();
}
private void save_button_Click(object sender, EventArgs e)
{
//Starts the file writer
using (StreamWriter sw = new StreamWriter("C:\\INET Portal Notes.txt"))
{
string CBRSame = cust_btn_text.Text;
if (cbr_same.Checked)
{
cust_callback_text.Text = CBRSame;
}
//Writes textboxes to the file
sw.WriteLine("**Name: " + cust_name_text.Text);
sw.WriteLine("**BTN: " + cust_btn_text.Text);
sw.WriteLine("**CBR: " + cust_callback_text.Text);
sw.WriteLine("**Modem: " + cust_modem_text.Text);
//Statements to write checkboxes to file
string checkBoxesLine = "**Lights:";
foreach (Control control in pnlCheckBoxes.Controls)
{
if (control is CheckBox)
{
CheckBox checkBox = (CheckBox)control;
if (checkBox.Checked && checkBox.Tag is string)
{
string checkBoxId = (string)checkBox.Tag;
checkBoxesLine += string.Format("{0}, ", checkBoxId);
}
}
}
//Newline for checkboxes
sw.WriteLine(checkBoxesLine);
//Continues textboxes to file
sw.WriteLine("**Troubleshooting: " + tshooting_text.Text);
sw.WriteLine("**Services Offered: " + services_offered_text.Text);
sw.WriteLine("**Other Notes: " + other_notes_text.Text);
sw.Flush();
}
}
//Button that will pull all the text from the text file and then show it in the notes textbox and also push to clipboard
private void generate_button_Click(object sender, EventArgs e)
{
//Loads the reader
StreamReader streamreader = new StreamReader("C:\\INET Portal Notes.txt");
//Reads the text from the INET Portal Notes.txt
notes_view_text.Text = "";
while (!streamreader.EndOfStream)
{
string read_line = streamreader.ReadToEnd();
notes_view_text.Text += read_line + "\n";
}
streamreader.Close();
//Copies text to clipboard for pasting into INET
Clipboard.SetText(notes_view_text.Text);
}
//Button to reset entire form
private void reset_form_button_Click(object sender, EventArgs e)
{
//Reset checkboxes panel
try
{
foreach (Control ctrl in pnlCheckBoxes.Controls)
{
if (ctrl.GetType() == typeof(CheckBox))
((CheckBox)ctrl).Checked = false;
}
//resets textboxes
cust_name_text.Clear();
cust_btn_text.Clear();
cust_callback_text.Clear();
cust_modem_text.Clear();
tshooting_text.Clear();
services_offered_text.Clear();
other_notes_text.Clear();
notes_view_text.Clear();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
}
I've not looked closely at your code, but I'd imagine you can simply hook to a TextChanged (or similar) property, then call the same code you were calling for your Save process.
Update the save process to use an in-memory stream (rather than writing to disk), or re-write it to use something more "fitting" for your new scenario eg a stringbuilder as was already suggested.
Does that help?
Ok I am going to try this again. I got more information now. I understand I can not use open and save dialogs and there is no database. So I am still kinda lost cause I was shown how to do it with open and save dialogs before. I am going to put what I am suppose to do and then so far the code I have. The code I have I have to build off and add too. I will also show what I am suppose to add to it. I am just trying to find the best way to understand this cause right now I am not. I am still new and I know the last couple days people have been trying to help me understand and then I was told it wasnt with the open and save dialog. Here is what I am suppose to do.
•Add a textbox named txtFilePath <--- already have that
•Add a button next to the above textbox that says “Load” (name it appropriately)<-already have that
•Add a button that says “Save” (name it appropriately) <-- already have this
•When thebutton “Load” is clicked, read the file specified in the textbox
(txtFilePath: Absolute path not relative) and add the objects found
within to the listbox<--- Not understanding
•When the user clicks the “Save” button, write the selected record to
the file specified in txtFilePath (absolute path not relative) without
truncating the values currently inside<-- not understanding
Here is the one part of code I have:`
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void addButton_Click(object sender, EventArgs e)
{
EditDialog newEmployeeDialog = new EditDialog();
if (newEmployeeDialog.ShowDialog() == DialogResult.OK)
{
employeeList.Items.Add(newEmployeeDialog.StaffMember);
}
}
private void deleteButton_Click(object sender, EventArgs e)
{
if (employeeList.SelectedIndex == -1)
return;
if (MessageBox.Show("Really delete this employee",
"Delete", MessageBoxButtons.YesNo,
MessageBoxIcon.Question)
== DialogResult.Yes)
{
employeeList.Items.Remove(
employeeList.SelectedItem);
}
}
private void editButton_Click(object sender, EventArgs e)
{
if (employeeList.SelectedIndex == -1)
return;
int employeeNum = employeeList.SelectedIndex;
EditDialog newEmployeeDialog = new EditDialog();
newEmployeeDialog.StaffMember =
(Employee)employeeList.SelectedItem;
if (newEmployeeDialog.ShowDialog() == DialogResult.OK)
{
employeeList.Items.RemoveAt(employeeNum);
employeeList.Items.Insert(employeeNum, newEmployeeDialog.StaffMember);
employeeList.SelectedIndex = employeeNum;
}
}
private void employeeList_SelectedIndexChanged(object sender, EventArgs e)
{
if (employeeList.SelectedIndex != -1)
{
Employee currentEmployee = (Employee)employeeList.SelectedItem;
firstName.Text = currentEmployee.FirstName;
lastName.Text = currentEmployee.LastName;
jobTitle.Text = currentEmployee.JobTitle;
}
else
{
firstName.Text = lastName.Text = jobTitle.Text = "";
}
}
`
Now I know you can not see the button click but I do have them mark. I know when you use open and save how it works. How I can go about this? I would use stream writer right.I understand that the user will type the path into the textbox and when the user hits load, it will load the file that they are specified. Now I am just trying to understand a code to be able to word this right.
would it be something like this:
String filePath = this.txtFilePath.Text;
since I need to name the textbox txtFilePath. I know some of you might say this is simple but when you are first learning it don't seem that simple. I have been trying something to help me understand since I do my college from home. Thank you for reading hoping to hear from you guys.
Update: Would it be something like this
Reading a file
private void Load_Click(object sender, EventArgs e)
{
StreamReader myReader = new StreamReader(C:\\")
txtFilePath.Text = my reader.read to end();
myReader.Close();
}
then there is writing a file
{
StreamWriter myWriter = new StreamWriter("C:\\test.txt", true);
myWriter.Write("Some text");
myWriter.WriteLine("Write a line");
myWriter.WriteLine("Line 2");
myWriter.Close();
}
If this is correct then I have to get it where if the file is not there for the notepad to pop up so they can add it then they can save it without deleting anything out the file or files.
Assuming the file contains a list of employee names, you should be able to load them into your listbox using something like this:
var filepath = txtFilePath.Text;
if (File.Exists(filepath))
{
var lines = File.ReadAllLines(filepath);
foreach (var line in lines)
employeeList.Items.Add(line);
}
Then assuming you want to add a new employee name to the file that the user just entered into the listbox:
var filepath = txtFilePath.Text;
if (File.Exists(filepath))
using (var sw = File.AppendText(filepath))
sw.WriteLine((string)employeeList.Text);
else
using (var sw = File.CreateText(filepath))
sw.WriteLine((string)employeeList.Text);
This hasn't been tested, but it should work nearly as-is...