Open/save multiple textbox values c# windows forms - c#

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)

Related

Reading editing and writing .bin file in C#

I just started my adventure with C#. I want to write simple program that will read .bin file with OpenFileDialog, edit part of the file, and save the file with SaveFileDialog.
Unfortunately I have some problems probably because I have to learn a lot. Here is part of my code for reading but I have problems to save same file. Basically I think problem is with starting address and ending address because I don't know how to declare this in write function.
OpenFileDialog ofd = new OpenFileDialog();
private void button1_Click(object sender, EventArgs e)
{
ofd.ShowDialog();
BinaryReader br = new BinaryReader(File.OpenRead(ofd.FileName));
br.Close();
}
SaveFileDialog sfd = new SaveFileDialog();
private void button2_Click(object sender, EventArgs e)
{
sfd.ShowDialog();
BinaryWriter br= new BinaryWriter(File.OpenWrite(sfd.FileName));
br.Close();
}
I want to write same file back the length of file is always 8192 bytes so start from 0x0000 until 0x1FFF.
If I get you correctly, you are trying to read from a file, edit it and save the edited file. I think what you are missing is the actual reading
string s = br.ReadString();
and writing
bw.Write(s);
to the file (bw is BinaryWriter).
check out a simple tutorial on reading and writing with binary reader/writer.

How to overwrite an existing html file from textbox in C#?

I'm trying to create a normal HTML editor where it's functions are similar to Windows Notepad. Let's say we've written a file and wanted to save it. So the SaveFileDialog comes up and asking us where we want to save it. Then we modified it, and in Notepad you usually just use Ctrl+S to save it again. And this time, no SaveFileDialog will show up. In other words, the existing file has been overwritten. This is what I wanted to achieve. Here's the code I have so far:
private void toolStripButton2_Click(object sender, EventArgs e)
{
SaveFileDialog sfd = default(SaveFileDialog);
string location = null;
string sourcecode = textBox1.Text;
sfd = new SaveFileDialog();
location = sfd.FileName;
if (string.IsNullOrEmpty(sfd.FileName))
{
saveAsToolStripMenuItem_Click(sender, e);
}
else
{
File.Copy(sfd.FileName, Path.Combine(location, Path.GetFileName(sfd.FileName)), true);
}
}

save as dialog to save TextBox Data into a file

I have one TextBox, It has some data.
There is a Button. So When I click the button, "save as " dialog should popup to save the text TextBox Data into a file.
I have tried various ways, but getting errors n error. Here I am giving you brief idea how I am writing code, If I am wrong please make me correct.
Or is there any other way to save TextBox Data into a file od my desired path.
protected void ButtonIDSaveAs_Click(object sender, EventArgs e)
{
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.Title = "Save an Image File";
saveFileDialog1.ShowDialog();
if (saveFileDialog1.FileName != "")
{
System.IO.FileStream fs =
(System.IO.FileStream)saveFileDialog1.OpenFile();
fs.Close();
}
}
Thanks
Vivek
SaveDialog.OpenFile creates a new file (overwriting an existing file with the same choosen name) and returns a Stream object that could be used as the constructor parameter for a StreamWriter.
So you could simply write
if (saveFileDialog1.FileName != "")
{
using(StreamWriter sw = new StreamWriter(saveFileDialog1.OpenFile()))
{
sw.Write(TextBox1.Text);
}
}

Filepath and textboxes

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...

how to show a txt file when clicking the button in c#

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();
}
}

Categories

Resources