I’m trying to develop my first application in C#, and I’m simply trying to read and write from a file. I’ve done hours of research, had mentors attempt to teach me, but its just not making sense to me.
I’ve got the beginning of my Form laid out, and what I believe to be the correct syntax for the StreamWriter I’m using, but the file name seems to be used in another process, and I have no idea which. Here’s the code I’m working with:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
namespace CustomerApplication
{
public partial class AddCustomerForm : Form
{
public AddCustomerForm()
{
InitializeComponent();
}
private void saveAndExitBtn_Click(object sender, EventArgs e)
{
StreamWriter sw = File.AppendText("test.csv");
sw.WriteLine("Test for Hope");
// next, retrieve hidden form's memory address
Form myParentForm = CustomerAppStart.getParentForm();
// now that we have the address use it to display the parent Form
myParentForm.Show();
// Finally close this form
this.Close();
}// end saveAndExitBtn_Click method
This is the line that Visual Studio doesn’t like :
StreamWriter sw = File.AppendText("test.csv");
Thanks for your time, in advance.
~TT
Educated guess here (based on but the file name seems to be used in another process) – you open the file for writing, but you never close it. So when you later try to write to it again, it fails.
Note that this can also happen if you have the file open in some other application (notepad, for instance).
You should be placing the creation of the stream in a
usingstatement to ensure it gets closed when you finish working with it: