web-dev-qa-db-fra.com

Le processus ne peut pas accéder au fichier car il est utilisé par un autre processus (le fichier est créé mais ne contient rien)

using System.IO;

class test
{
    public static void Main()
    {

        string path=@"c:\mytext.txt";

        if(File.Exists(path))
        {
            File.Delete(path);
        }


        FileStream fs=new FileStream(path,FileMode.OpenOrCreate);
        StreamWriter str=new StreamWriter(fs);
        str.BaseStream.Seek(0,SeekOrigin.End); 
        str.Write("mytext.txt.........................");
        str.WriteLine(DateTime.Now.ToLongTimeString()+" "+DateTime.Now.ToLongDateString());
        string addtext="this line is added"+Environment.NewLine;
        File.AppendAllText(path,addtext);  //Exception occurrs ??????????
        string readtext=File.ReadAllText(path);
        Console.WriteLine(readtext);
        str.Flush();
        str.Close();

        Console.ReadKey();
  //System.IO.IOException: The process cannot access the file 'c:\mytext.txt' because it is //being used by another process.
  // at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)

    }
}
9
sunil

Essaye ça

string path = @"c:\mytext.txt";

if (File.Exists(path))
{
    File.Delete(path);
}

{ // Consider File Operation 1
    FileStream fs = new FileStream(path, FileMode.OpenOrCreate);
    StreamWriter str = new StreamWriter(fs);
    str.BaseStream.Seek(0, SeekOrigin.End);
    str.Write("mytext.txt.........................");
    str.WriteLine(DateTime.Now.ToLongTimeString() + " " + 
                  DateTime.Now.ToLongDateString());
    string addtext = "this line is added" + Environment.NewLine;
    str.Flush();
    str.Close();
    fs.Close();
    // Close the Stream then Individually you can access the file.
}

File.AppendAllText(path, addtext);  // File Operation 2

string readtext = File.ReadAllText(path); // File Operation 3

Console.WriteLine(readtext);

Dans chaque opération de fichier, le fichier sera ouvert et doit être fermé avant l'ouverture. De même, dans l'opération 1, vous devez fermer le flux de fichiers pour les autres opérations.

15
Gokul E

Vous écrivez dans le fichier avant de fermer votre flux de fichiers:

using(FileStream fs=new FileStream(path,FileMode.OpenOrCreate))
using (StreamWriter str=new StreamWriter(fs))
{
   str.BaseStream.Seek(0,SeekOrigin.End); 
   str.Write("mytext.txt.........................");
   str.WriteLine(DateTime.Now.ToLongTimeString()+" "+DateTime.Now.ToLongDateString());
   string addtext="this line is added"+Environment.NewLine;

   str.Flush();

}

File.AppendAllText(path,addtext);  //Exception occurrs ??????????
string readtext=File.ReadAllText(path);
Console.WriteLine(readtext);

Le code ci-dessus devrait fonctionner, en utilisant les méthodes que vous utilisez actuellement. Vous devez également examiner l'instruction using et encapsuler vos flux dans un bloc using.

4
Paddy

File.AppendAllText Ne connaît pas le flux que vous avez ouvert, il essaiera donc en interne d'ouvrir à nouveau le fichier. Étant donné que votre flux bloque l'accès au fichier, File.AppendAllText Échouera, levant l'exception que vous voyez.

Je vous suggère d'utiliser à la place str.Write Ou str.WriteLine, Comme vous le faites déjà ailleurs dans votre code.

Votre fichier est créé mais ne contient rien car l'exception est levée avant l'appel de str.Flush() et str.Close().

2
Yogster