Sto giocando con C# e ho riscontrato un problema. Quando provo a creare un nuovo file, il programma si interrompe e dice che il file è utilizzato da un altro processo. Probabilmente è qualcosa di stupido che ho trascurato, ma non riesco a capirlo!Eccezione C#. Il file viene utilizzato da un altro processo
Ecco il mio codice:
using System;
using System.IO;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace myNameSpace
{
public partial class MainWindow : Form
{
public static string folderPath = @"fullpath";
public MainWindow()
{
InitializeComponent();
StoredTb.Text = folderPath;
String[] files = Directory.GetFiles(folderPath);
foreach (string file in files)
myDropDown.Items.Add(Path.GetFileNameWithoutExtension(file));
}
private void myDropDown_SelectedIndexChanged(object sender, EventArgs e)
{
this.BeginInvoke(new MethodInvoker(myDropDown_invokedMethod));
}
private void myDropDown_invokedMethod()
{
string fullpath = MainWindow.folderPath + myDropDown.SelectedText + ".txt";
StreamReader sr = new StreamReader(fullpath);
NameTb.Text = myDropDown.SelectedText;
DescriptionTb.Text = sr.ReadToEnd();
sr.Close();
}
private void SaveBtn_Click(object sender, EventArgs e)
{
File.Create(NameTb.Text + ".txt");
TextWriter tw = new StreamWriter(NameTb.Text + ".txt"); /* this is where the problem occurs */
tw.WriteLine("The very first line!");
tw.Close();
}
}
}
Scusate per il lungo frammento di codice, ma dal momento che non sono sicuro dove il problema proviene da ho dovuto includere praticamente tutto.
Grazie! Ha funzionato. Accetterò tra 6 minuti (quindi non mi permetta di accettare ancora) –