Fichier déjà utilisé comment faire

DragZ -  
 Utilisateur anonyme -
Bonjour,
Je me permet de vous contacter car j'ai un problème, je souhaiterai compresser des fichiers, je réussissais jusqu'au moment des tests ou je me suis rendu compte que les fichiers pouvais être déja utilisé voici mon code
  using (FileStream originalFileStream = fileToCompress.OpenRead())
            {
                if ((File.GetAttributes(fileToCompress.FullName) &
                   FileAttributes.Hidden) != FileAttributes.Hidden & fileToCompress.Extension != ".gz")
                {
                    using (FileStream compressedFileStream = File.Create(fileToCompress.FullName + ".gz"))
                    {
                        using (GZipStream compressionStream = new GZipStream(compressedFileStream,
                           CompressionMode.Compress))
                        {
                            originalFileStream.CopyTo(compressionStream);
                        }
                    }
                }
            }

L'erreur : "Le processus ne peut pas accéder au fichier xxx

Configuration: Windows / Chrome 88.0.4324.96

7 réponses

  1. Utilisateur anonyme
     
    Bonsoir

    y'a malheureusement pas vraiment moyen de savoir si un autre logiciel utilise un fichier (et même parfois quand c'est ton propre logiciel...)

    Utilise un try/catch, si ça va dans le catch informe l'utilisateur et passe au fichier suivant
    0
  2. DragZ
     
    Il n'y a donc aucun moyen de récupérer le fichier si il est utilisé ?
    0
  3. Utilisateur anonyme
     
    Qu’est ce que tu appelles récupérer?
    0
  4. DragZ
     
    Quand il est utilisé par un autre processus j'aimerai pourvoir le compresser malgré le fait qu'il sois déjà utilisé
    0
  5. Vous n’avez pas trouvé la réponse que vous recherchez ?

    Posez votre question
  6. Utilisateur anonyme
     
    A priori si tu as une erreur c’est que ça ne doit être possible.

    D’ou ma proposition d’alerter l’utilisateur pour qu’il le libère avant de recommencer.

    0
  7. Pat
     
    Bonsoir,

    L’exemple de code suivant montre comment verrouiller une partie d’un fichier pour qu’un autre processus ne puisse pas accéder à cette partie du fichier, même s’il dispose d’un accès en lecture/écriture au fichier, puis déverrouille la partie spécifiée du fichier. Exécutez le programme simultanément dans différentes fenêtres de commande et examinez à l’aide des différentes options d’entrée de la console.

    using System;
    using System.IO;
    using System.Text;
    
    class FStreamLock
    {
        static void Main()
        {
            UnicodeEncoding uniEncoding = new UnicodeEncoding();
            string lastRecordText =
                "The last processed record number was: ";
            int textLength = uniEncoding.GetByteCount(lastRecordText);
            int recordNumber = 13;
            int byteCount =
                uniEncoding.GetByteCount(recordNumber.ToString());
            string tempString;
    
            using(FileStream fileStream = new FileStream(
                "Test#@@#.dat", FileMode.OpenOrCreate,
                FileAccess.ReadWrite, FileShare.ReadWrite))
            {
                // Write the original file data.
                if(fileStream.Length == 0)
                {
                    tempString =
                        lastRecordText + recordNumber.ToString();
                    fileStream.Write(uniEncoding.GetBytes(tempString),
                        0, uniEncoding.GetByteCount(tempString));
                }
    
                // Allow the user to choose the operation.
                char consoleInput = 'R';
                byte[] readText = new byte[fileStream.Length];
                while(consoleInput != 'X')
                {
                    Console.Write(
                        "\nEnter 'R' to read, 'W' to write, 'L' to " +
                        "lock, 'U' to unlock, anything else to exit: ");
    
                    if((tempString = Console.ReadLine()).Length == 0)
                    {
                        break;
                    }
                    consoleInput = char.ToUpper(tempString[0]);
                    switch(consoleInput)
                    {
                        // Read data from the file and
                        // write it to the console.
                        case 'R':
                            try
                            {
                                fileStream.Seek(0, SeekOrigin.Begin);
                                fileStream.Read(
                                    readText, 0, (int)fileStream.Length);
                                tempString = new String(
                                    uniEncoding.GetChars(
                                    readText, 0, readText.Length));
                                Console.WriteLine(tempString);
                                recordNumber = int.Parse(
                                    tempString.Substring(
                                    tempString.IndexOf(':') + 2));
                            }
    
                            // Catch the IOException generated if the
                            // specified part of the file is locked.
                            catch(IOException e)
                            {
                                Console.WriteLine("{0}: The read " +
                                    "operation could not be performed " +
                                    "because the specified part of the " +
                                    "file is locked.",
                                    e.GetType().Name);
                            }
                            break;
    
                        // Update the file.
                        case 'W':
                            try
                            {
                                fileStream.Seek(textLength,
                                    SeekOrigin.Begin);
                                fileStream.Read(
                                    readText, textLength - 1, byteCount);
                                tempString = new String(
                                    uniEncoding.GetChars(
                                    readText, textLength - 1, byteCount));
                                recordNumber = int.Parse(tempString) + 1;
                                fileStream.Seek(
                                    textLength, SeekOrigin.Begin);
                                fileStream.Write(uniEncoding.GetBytes(
                                    recordNumber.ToString()),
                                    0, byteCount);
                                fileStream.Flush();
                                Console.WriteLine(
                                    "Record has been updated.");
                            }
    
                            // Catch the IOException generated if the
                            // specified part of the file is locked.
                            catch(IOException e)
                            {
                                Console.WriteLine(
                                    "{0}: The write operation could not " +
                                    "be performed because the specified " +
                                    "part of the file is locked.",
                                    e.GetType().Name);
                            }
                            break;
    
                        // Lock the specified part of the file.
                        case 'L':
                            try
                            {
                                fileStream.Lock(textLength - 1, byteCount);
                                Console.WriteLine("The specified part " +
                                    "of file has been locked.");
                            }
                            catch(IOException e)
                            {
                                Console.WriteLine(
                                    "{0}: The specified part of file is" +
                                    " already locked.", e.GetType().Name);
                            }
                            break;
    
                        // Unlock the specified part of the file.
                        case 'U':
                            try
                            {
                                fileStream.Unlock(
                                    textLength - 1, byteCount);
                                Console.WriteLine("The specified part " +
                                    "of file has been unlocked.");
                            }
                            catch(IOException e)
                            {
                                Console.WriteLine(
                                    "{0}: The specified part of file is " +
                                    "not locked by the current process.",
                                    e.GetType().Name);
                            }
                            break;
    
                        // Exit the program.
                        default:
                            consoleInput = 'X';
                            break;
                    }
                }
            }
        }
    }
    0
    1. Utilisateur anonyme
       
      Bonjour Pat

      Merci pour cet exemple.

      Cependant, en l’état, il est illisible sur le forum, pour tes prochaines interventions voir ce petit tuto sur les balises de code https://codes-sources.commentcamarche.net/faq/11288-les-balises-de-code
      0
      1. Pat > Utilisateur anonyme
         
        Bonjour,

        Merci pour le tuto , le code étant long j'ai eu un petit pb technique , comme je code en direct je vais un peu vite :-)
        0
  8. Utilisateur anonyme
     
    Bonjour

    Pat, j'ai pris le temps de tester ton code ce matin.

    Ca ne répond pas au problème de DragZ, qui veut zipper un fichier qui est bloqué par un autre processus...

    Ton code montre le fonctionnement du coté du "bloqueur" du fichier.
    0