2012-03-26 6 views
7

Estoy escribiendo un programa de registrador de teclas simple (para fines no maliciosos).El uso de File.AppendAllText provoca un error "Proceso no puede acceder al archivo, ya está en uso"

Nota: Esta es con .NET 4.0 Client Profile

Cada vez que inicie el programa, me sale este error:

The process cannot access the file 'C:\Users\.. ..\bin\Debug\log.log' because it is being used by another process. 

Aquí está mi código principal:

using System; 
using System.Collections.Generic; 
using System.Drawing; 
using System.Windows.Forms; 
using System.ComponentModel; 
using System.IO; 
using System.Text; 

namespace Logger 
{ 
    public partial class MainForm : Form 
    { 
     public string cWin = null; 
     public static string nl = Environment.NewLine; 

     public MainForm() 
     { 
      InitializeComponent(); 
     } 

     public static DialogResult AskOverwrite() 
     { 
      DialogResult result = MessageBox.Show("Log already exists. Overwrite?", 
       "Overwrite?", 
       MessageBoxButtons.YesNo, 
       MessageBoxIcon.Question); 

      return result; 
     } 

     private void MainForm_Resize(object sender, EventArgs e) 
     { 

      if (FormWindowState.Minimized == this.WindowState) 
      { 
        systray.Visible = true; 
        this.Hide();  
      } 
      else if (FormWindowState.Normal == this.WindowState) 
      { 
        systray.Visible = false; 
      } 
     } 

     private void SystrayMouse_DoubleClick(object sender, MouseEventArgs e) 
     { 
      this.Show(); 
      this.WindowState = FormWindowState.Normal; 
     } 

     private void HookManager_KeyPress(object sender, KeyPressEventArgs e) 
     { 
      if (Program.run) 
      { 
       output.AppendText(string.Format(e.KeyChar.ToString())); 
       File.AppendAllText(Program.file, e.KeyChar.ToString()); 
      } 
     } 

     private void Start_Click(object sender, EventArgs e) 
     { 
      if (!Program.run) 
      { 
       if (File.Exists(Program.file)) 
       { 
        if (AskOverwrite() == DialogResult.Yes) 
        { 
         File.Create(Program.file); 
        } 
       } 

       Program.run = true; 
       output.AppendText(string.Format("Logging started - {1}{0}", nl, System.DateTime.Now)); 
       File.AppendAllText(Program.file, string.Format("Logging started - {1}{0}", nl, System.DateTime.Now)); 
      } 
      else 
      { 
       output.AppendText(string.Format("Logging already started!{0}", nl)); 
      } 
     } 

     private void Stop_Click(object sender, EventArgs e) 
     { 
      if (Program.run) 
      { 
       Program.run = false; 
       output.AppendText(string.Format("{0}Logging stopped - {1}{0}", nl, System.DateTime.Now)); 
       File.AppendAllText(Program.file, string.Format("{0}Logging stopped - {1}{0}", nl, System.DateTime.Now)); 
      } 
      else 
      { 
       output.AppendText(string.Format("Logging already stopped!{0}", nl)); 
      } 
     } 

     private void getWindowTimer_Tick(object sender, EventArgs e) 
     { 
      if (cWin != CurrentWindow.GetActiveWindow() &&Program.run) 
      { 
       cWin = CurrentWindow.GetActiveWindow(); 
       if (cWin != null) 
       { 
        output.AppendText(string.Format("{0}Window - {1}{0}", nl, cWin)); 
        File.AppendAllText(Program.file, string.Format("{0}Window - {1}{0}", nl, cWin)); 
       } 
      } 
     } 
    } 
} 

¿Por qué está pasando esto? Estaba bien cuando estaba usando esta declaración a escribir en el fichero:

using (StreamWriter sr = new StreamWriter(Program.file)) 
{ 
    sr.Write(string.Format("texthere"); 
} 

Pero dejó de funcionar cuando me cambié a simple uso:

File.AppendAllText(Program.file, string.Format("texthere"); 
+1

¿Qué versión de .Net se dirige? – Brannon

+0

@Brannon Pregunta editada –

+0

¿Esto parecerá obvio, pero no tiene su archivo de registro abierto en otro programa mientras intenta escribir en él? –

Respuesta

23

Veo una

File.Create(Program.file); 

que es innecesario y probablemente sea el problema directo aquí.

No solo crea un archivo vacío sino que también abre y devuelve un objeto FileStream que no se cierra en ningún lugar. El FileStream abierto no se puede compartir, por lo que hace que falle AppendAllText().

Basta con retirar esa línea, AppendAllText() incluye la lógica para create the file if it does not already exist

+0

Bueno, eso parece bastante extraño, ¡pero funciona! –

Cuestiones relacionadas