Reputation: 41
I have a method that saves the text from a text box into a txt file but I get an System.IO.IOException error every time I back out of the SaveFileDialog.
static OpenFileDialog ofd = new OpenFileDialog();
static SaveFileDialog sfd = new SaveFileDialog();
static String cp;
private void SaveClass() {
sfd.DefaultExt = "txt";
sfd.Filter = "Text Files | *.txt";
if (sfd.ShowDialog() == DialogResult.OK) {
cp = sfd.FileName;
File.Create(cp);
File.WriteAllLines(@cp, StudentTextBox.Text.Split(new String[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries));
}
}
Visual Studio highlights the code that starts with "File.WriteAllLines" and says that's where I'm getting the error. Thanks.
Exact error message:
An unhandled exception of type 'System.IO.IOException' occurred in mscorlib.dll
Additional information: The process cannot access the file 'C:\Users\ktfjulien\Documents\poop.txt' because it is being used by another process.
EDIT: Thank you, I no longer get the error message but everything I save into the text box is written onto one line, regardless if the text is delimited by new lines or not.
Upvotes: 0
Views: 948
Reputation: 186833
You have no need to create the file, File.WriteAllLines
will do it for you (or clear up the file if it exists):
private void SaveClass() {
sfd.DefaultExt = "txt";
sfd.Filter = "Text Files | *.txt";
if (sfd.ShowDialog() == DialogResult.OK)
File.WriteAllLines(sfd.FileName, StudentTextBox.Text
.Split(new String[] { Environment.NewLine },
StringSplitOptions.RemoveEmptyEntries));
}
Upvotes: 1
Reputation: 30813
You do not need to do File.Create(cp);
to write to a file. This is the cause of the error. Instead, directly do:
cp = sfd.FileName;
FileStream fs = File.OpenWrite(cp);
And if you want to use the StreamWriter
instead of FileStream
, use the FileStream
as the input for your StreamWriter
StreamWriter sw = new StreamWriter(fs);
Or, you could also directly use File.WriteAllLines
as you show - don't use the File.Create
:
if (sfd.ShowDialog() == DialogResult.OK) {
cp = sfd.FileName;
//File.Create(cp); //remove this
File.WriteAllLines(@cp, StudentTextBox.Text.Split(new String[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries));
}
Upvotes: 3
Reputation: 7352
When you are creating file using File.Create()
this file is already used by File.Create()
you need close that file before use another place so before writing text to the file close file writer
var file = File.Create(cp);
file.Close();
complete working solution
static OpenFileDialog ofd = new OpenFileDialog();
static SaveFileDialog sfd = new SaveFileDialog();
static String cp;
private void SaveClass()
{
sfd.DefaultExt = "txt";
sfd.Filter = "Text Files | *.txt";
if (sfd.ShowDialog() == DialogResult.OK)
{
cp = sfd.FileName;
var file = File.Create(cp);
file.Close();
File.WriteAllLines(@cp, StudentTextBox.Text.Split(new String[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries));
}
}
Upvotes: 1