Append input into text file instead of replacing it - c#

I'm trying to take the data from two text boxes, and writing it to file without replacing the current stuff already there when a button is pressed. This is what I have so far:
private void button1_Click_1(object sender, EventArgs e)
{
using (StreamWriter sw1 = new StreamWriter("DataNames.txt"))
{
sw1.WriteLine(textBox1.Text);
}
using (StreamWriter sw2 = new StreamWriter("DataNumbers.txt"))
{
sw2.WriteLine(textBox2.Text);
}
}
Right now it takes the input, and replaces whatever is currently in the files so then there is only one line, instead of just adding it to the list. Thanks for the help.

//using (StreamWriter sw1 = new StreamWriter("DataNames.txt"))
//{
// sw1.WriteLine(textBox1.Text);
//}
System.IO.File.AppendAllText("DataNames.txt", textBox1.Text);

Use StreamWriter Constructor (String, Boolean) constructor and pass true for append.
true to append data to the file; false to overwrite the file. If the specified file does not exist, this parameter has no effect, and
the constructor creates a new file.
In your code pass true like:
using (StreamWriter sw1 = new StreamWriter("DataNames.txt",true))

Try this
using (StreamWriter sw2 = new StreamWriter("DataNumbers.txt", true))
{
sw2.WriteLine(textBox2.Text);
}
Second argument true tells that file needs to be appended instead of overwriting. StreamWriter(String, Boolean)

Switch the
new StreamWriter("DataNumbers.txt")
to
File.CreateText("DataNames.txt")
You can find more info at:
http://msdn.microsoft.com/en-us/library/system.io.file.appendtext.aspx

You are making two separate instance of stream writer, and they are both attempting to write to the same file, so they are competing with each other - that's why you are seeing the overwriting.
If you want to add text to the end of a file, the best way to do so is probably File.AppendAllText: http://msdn.microsoft.com/en-us/library/ms143356.aspx
private void button1_Click_1(object sender, EventArgs e)
{
System.IO.File.AppendAllText("DataNames.txt", textBox1.Text + textBox2.Text);
}
AppendAllText is quite useful if you are doing small, relatively infrequent appends as you can just send strings into it without thinking as opposed to making sure you are using your stream writer.

Related

"Cannot access file" when writing to file

I have been working on a clone of notepad and I have run into a problem.
When I try to write the text in the textbox into a file which I create I get the exception:
The process cannot access the file 'C:\Users\opeyemi\Documents\b.txt'
because it is being used by another process.
Below is the code I have written. I would really appreciate any advise on what I should do next.
private void Button_Click_1(object sender, RoutedEventArgs e)
{
SaveFileDialog TextFile = new SaveFileDialog();
TextFile.ShowDialog();
// this is the path of the file i wish to save
string path = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments),TextFile.FileName+".txt");
if (!System.IO.File.Exists(path))
{
System.IO.File.Create(path);
// i am trying to write the content of my textbox to the file i created
System.IO.StreamWriter textWriter = new System.IO.StreamWriter(path);
textWriter.Write(textEditor.Text);
textWriter.Close();
}
}
You must "protect" your StremWriter use (both read and write) in using, like:
using (System.IO.StreamWriter textWriter = new System.IO.StreamWriter(path))
{
textWriter.Write(textEditor.Text);
}
no .Close() necessary.
You don't need the System.IO.File.Create(path);, because the StreamWriter will create the file for you (and the Create() returns a FileStream that you keep open in your code)
Technically you could:
File.WriteAllText(path, textEditor.Text);
this is all-in-one and does everything (open, write, close)
Or if you really want to use the StreamWriter and the File.Create:
using (System.IO.StreamWriter textWriter = new System.IO.StreamWriter(System.IO.File.Create(path)))
{
textWriter.Write(textEditor.Text);
}
(there is a StreamWriter constructor that accepts FileStream)

Create new file with StreamWriter everytime the program is executed

I am making simple tool for manipulating images in a database. I want to show the output result in a txt file and because the outcome may be different each time, I want the file to be rewritten with the fresh data every time the data is executed.
Also I want (if possible) to use some default location where the txt file will be created even though I have an App.Config file and that's also an option.
The problem I am having is with this code:
string Resultfile =
System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) +
"\\PictureStatus.txt";
FileStream strm = new FileStream(Resultfile , FileMode.Create);
TextWriter tw = new StreamWriter(strm);
This populates the PictureStatus.txt only once and then I get the same text over and over again. I noticed that if I use some random destination the file is updated. Not sure if it's just random behavior or have something to do with using MyDocuments, but what I need is a way to be sure that I'll rewrite the file with the new data each time, and if possible, use some default destination that will work for other people.
You can try something like this
public partial Form2 : Form
{
public string path = Environment.CurrentDirectory + "/" + "Name.txt";
public Form2()
{
InitializeComponent();
if (!File.Exists(path))
{
File.Create(path);
}
}
private void button2_Click(object sender, EventArgs e)
{
using (StreamWriter sw = new StreamWriter(path, true))
{
sw.WriteLine("This text will be writen in the txt file", true);
sw.Close();
}
}
}
I have add to the button, when I pressed it will be written in the next line every time. If you remove "true" from code, it will be overwritten every time.

Streamreader to display

I'm still on my first step on C# and this is my first post/question.
How do I implement Streamreader to Display(output)
Like after clicking the Dataretrieve button I want to retrieve the data located on "D:\Savedata.txt" and display it on the lblDisplay
This is my code, am I missing something?
void DataretrieveClick(object sender, EventArgs e)
{
StreamReader read = File.OpenText("D:\\Savedata.txt");
lblDisplay.Text = "Last Name: " +textBox1.Text.Trim();
read.Close();
}
Something like this should be what you're looking for.
void DataretrieveClick(object sender, EventArgs e)
{
using (StreamReader reader = File.OpenText("D:\\Savedata.txt"))
{
lblDisplay.Text = reader.ReadToEnd();
}
}
When you create an instance of a class that implements interface IDisposable, you should wrap it in a using() statement to make sure the resources for it are freed when you leave the using() scope. Also, you can look over the documentation for StreamReader here which should help you see what's available.
There is very handy static method ReadAllText in File class, which will open a text file, read all lines of the file, and then close the file:
lblDisplay.Text = File.ReadAllText("D:\\Savedata.txt");
Internally this method does exactly what you are trying to implement (creates StreamReader and reads all characters from the current position to the end of the stream):
using (var reader = new StreamReader(path, Encoding.UTF8, true, 0x400, true))
{
return reader.ReadToEnd();
}
You're looking for read.ReadToEnd().

Write data from Textbox into text file in ASP.net with C#

I have a textbox where a user can input their email, what I want to do is make it so that when they click a submit button. That email will be saved into a text file ( on my server ) called emails.txt
I managed to get this working using System.IO and then using the File.WriteAll method. However I want to make it so that it will add the email to the list ( on a new line ) rather then just overwriting whats already in there.
I've seen people mention using Append, but I can't quite grasp how to get it working.
This is my current code (that overwrites instead of appending).
public partial class _Default : Page
{
private string path = null;
protected void Page_Load(object sender, EventArgs e)
{
path = Server.MapPath("~/emails.txt");
}
protected void emailButton_Click(object sender, EventArgs e)
{
File.WriteAllText(path, emailTextBox.Text.Trim());
confirmEmailLabel.Text = "Thank you for subscribing";
}
}
You can use StreamWriter to get working with text file. The WriteLine method in true mode append your email in new line each time....
using (StreamWriter writer = new StreamWriter("email.txt", true)) //// true to append data to the file
{
writer.WriteLine("your_data");
}
From the official MSDN documentation:
using (StreamWriter w = File.AppendText("log.txt"))
{
MyWriteFunction("Test1", w);
MyWriteFunction("Test2", w);
}
Use StreamWriter in Append mode. Write your data with WriteLine(data).
using (StreamWriter writer = new StreamWriter("emails.txt", true))
{
writer.WriteLine(email);
}
Seems like a very easy question with a very easy answer: Open existing file, append a single line
If you post the current code, we can modify that to append instead of overwrite.

save file without using save file dialog

I am working on this project still and I am running into a problem. Well here is what I need to do.
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 and handle any exceptions that arise.
Ok here is my code:
private void Save_Click(object sender, EventArgs e)
{
string filePath = txtFilePath.Text;
if (!File.Exists(filePath))
{
FileStream fs = File.Create(filePath);
fs.Close();
}
using (FileStream fs = new FileStream(filePath, FileMode.Create, FileAccess.Write))
{
using (StreamWriter sw = new StreamWriter(fs))
{
foreach (string line in employeeList.Items)
{
sw.WriteLine(line);
}
}
}
}
Now when I go onto my program and want to save something from the employeelist.text that its not being saved to the place I am saving it at. I don;t know if I am missing something in my code or what but it will not save. Here is an example:
I add a person name to this list in employeelist and in the textbox I
have a file called C:\employess\employeelist.txt I want to save it to.
I click the save button then I go to that employeelist and it is not
being saved.
I don't know what I am doing wrong I have been looking online for a solution but I haven't found anything yet. Thanks
Some things to double-check:
Make sure you don't have the employeelist.txt file open when you're testing
Make sure you don't have invalid characters in your file name
Make sure your application has permission to save the file to the location you specified
Use the debugger to step-through your code and look for swallowed exceptions -- there must be a reason the file is not created.
Check that your Save_Click event is wired up to your button -- is the code in your example even running?
Once you check those things, you may want to follow this example for the create vs. append requirement of your project:
string path = txtFilePath.Text;
// This text is added only once to the file.
if (!File.Exists(path))
{
using (StreamWriter sw = File.CreateText(path))
{
foreach (var line in employeeList.Items)
sw.WriteLine(line.ToString());
}
}
else
{
using (StreamWriter sw = File.AppendText(path))
{
foreach (var line in employeeList.Items)
sw.WriteLine(line.ToString());
}
}
This will create the file if it doesn't exist, or append to it if it does.
Checking that the file exists and then creating it is a bit unnecessary as this can all be handled by the StreamWriter/FileStream parts. So your above function can be simplified into the following:
public void Save_Click(object sender, EventArgs e)
{
StreamWriter file =
new StreamWriter(txtFilePath.Text, true);//Open and append
foreach (object item in employeeList.Items) {
file.WriteLine(item.toString());
}
file.Close();
}
[Updated]
What are the types of txtFilePath and employeeList the former suggests it's a text box, the later suggests it's bound to a non-GUI element perhaps? (WAG)
You might also want to append a blank line at the end so that on further saves you can tell it was an append rather than one long list (depending on your needs of course)
Starting with .Net Framework 4 you can do it like this:
private void Save_Click(object sender, EventArgs e)
{
File.AppendAllLines(txtFilePath.Text, employeeList.Items);
}
Of course, you probably would want to add a check to have a valid path and a valid enumeration of strings.
If the path looks like a relative one (i.e. doesn't begin with a drive letter), then it will be interpreted that way.
If you put a full path in the text box, does the file get saved in the proper place? If so, perhaps this is what was intended.
If the user doesn't put in a full path, do you have a way to make it one (for example, just sticking C:\ at the beginning)? Or at least can you tell when there isn't a full path, and reject the request?

Categories