I am making simple text editor and got problems with saving. So I have 2 codes for saving, one is to save file using button and another ctrl+s keyboard shortcut, when saving with button everything works perfectly, but when i save with shortcut i get this error:
"process cannot access file because it's used by another process"
here is my code for button save: `
saveFileDialog1.FileName = currentname;
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
StreamWriter writer = new StreamWriter(saveFileDialog1.OpenFile());
writer.WriteLine(richTextBox1.Text);
writer.Dispose();
writer.Close();
//so i have tabs in my editor so user can switch between them.
//and this is the only way i found which tab is opened now.
for (int i = 0; i < labels.Count; i++)
{
//i created new class that holds some variables including "isUsed"
//and Label itself.
if (labels[i].isUsed)
{
labels[i].Text = Path.GetFileName(saveFileDialog1.FileName);
labels[i].setText(labels[i].Text);
labels[i].path = saveFileDialog1.FileName;
break;
}
}
}`
script above works normally, but the script below doesn't:
public void save(){
bool found = false;
//that is class i made.
AdvancedLabel label = new AdvancedLabel();
//I hold all tabs in "Labels" List.
for (int i = 0; i < labels.Count; i++)
{
//so if loop found the tab that is opened now...
if (labels[i].isUsed)
{
label = labels[i];
found = true;
break;
}
}
if (found)
{
try
{
label.label.Text.Remove(label.label.Text.Length - 1);
//here i always get this error.
StreamWriter writer = new StreamWriter(label.path);
writer.WriteLine(richTextBox1.Text);
label.setText(label.Text.Remove(label.Text.Length - 1));
writer.Dispose();
writer.Close();
}
catch (Exception e)
{
status.Text = "status: " + e.Message + ". Failed to save :(";
}
}
}
Here is the full error:
An unhandled exception of type 'System.IO.IOException' occurred in mscorlib.dll
Additional information: The process cannot access the file 'C:\Users\nika\Desktop\dd.html' because it is being used by another process.
EDIT:
thanks to you all guys, as i understood i should be using "using" statement and here is waht i came up with:
I forgot to mention that i am also opening file using stramreader. I changed it to "Using" statement but same things happen, even tho i am now using: File.appendalltext statement. This also works, but only if i save with button.
here is how i changed it (file opener not writers): `
using (var sr = new StreamReader(openFileDialog1.FileName))
{
bool found = false;
for (int i = 0; i < labels.Count; i++)
{
if (labels[i].path == openFileDialog1.FileName)
{
found = true;
break;
}
}
if (!found)
{
richTextBox1.Text = "";
richTextBox1.Text = sr.ReadToEnd();
spawnLabel();
}
}`
ps(this sounds so stupid)
as @GauravKP suggested:
any help will be appreciated! thanks!
--Nick.