2013-09-23 13 views
5

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.

risposta

9

tuo problema è che File.Create aprirà una stream che consente di fare ciò che ti piace al file:

http://msdn.microsoft.com/en-us/library/d62kzs03.aspx

Un FileStream che fornisce accesso in lettura/scrittura al file specificato nel percorso.

Pertanto, tecnicamente, è già in uso.

Basta rimuovere il File.Create del tutto. Lo StreamWriter gestirà la creazione del file se non esiste.

Inoltre, investire nei costrutti using per smaltire correttamente anche le connessioni dei file. Aiuterà a evitare questo in futuro.

+0

Grazie! Ha funzionato. Accetterò tra 6 minuti (quindi non mi permetta di accettare ancora) –

1

Usa

myDropDown_invokedMethod(); 

invece di

this.BeginInvoke(new MethodInvoker(myDropDown_invokedMethod)); 
+0

Grazie! Non è stato quello che ha causato l'eccezione, ma mi assicurerò di cambiarlo. –

0

Questo perché File.Create (NameTb.Text + ".txt"); mantiene il file aperto:

uso Prova a modificare:

private void SaveBtn_Click(object sender, EventArgs e) 
    { 
     using(Stream stream = File.Create(NameTb.Text + ".txt")) 
     { 
      TextWriter tw = new StreamWriter(stream); /* this is where the problem was */ 
      tw.WriteLine("The very first line!"); 
      tw.Close(); 
     } 
    } 

Questo wil forzare il File.Create da smaltire quando il metodo ha uscite. Lo smaltimento chiuderà il filehandle (handle non gestito win32). Altrimenti il ​​file verrà chiuso dal garbage collector, ma non si sa mai quando.

1

File.Create restituisce un oggetto FileStream che contiene il file. Dovresti usare questo oggetto per ulteriori compiti.

var fileStream = File.Create(NameTb.Text + ".txt"); 
//... do all the writing using fileStream 
fileStream.Close(); 

o si potrebbe fare proprio

var fs = File.Create(NameTb.Text + ".txt"); 
fs.Close(); 
TextWriter tw = new StreamWriter(NameTb.Text + ".txt"); 
tw.WriteLine("The very first line!"); 
tw.Close(); 
1

Il tuo problema sembra essere in SaveBtn_Click evento, si utilizza il file di destinazione due volte per la scrittura:

File.Create(NameTb.Text + ".txt"); 
TextWriter tw = new StreamWriter(NameTb.Text + ".txt"); 

rimuovere questa riga:

File.Create(NameTb.Text + ".txt"); 
1

Come per MSDN il File.Create Method (String) utilizza un FileStream che nel tuo caso non viene chiuso. Usa qualcosa come questo:

FileStream fs = new FileStream(NameTb.Text + ".txt"); 
File.Create(fs); 
fs.Close(); 

o @Muctadir Dinar

var fileStream = File.Create(NameTb.Text + ".txt"); 
//... do all the writing using fileStream 
fileStream.Close(); 
Problemi correlati