Fichier déjà utilisé comment faire

Fermé
DragZ - Modifié le 27 janv. 2021 à 17:19
 Utilisateur anonyme - 31 janv. 2021 à 09:18
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
A voir également:

7 réponses

Utilisateur anonyme
27 janv. 2021 à 18:17
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
Il n'y a donc aucun moyen de récupérer le fichier si il est utilisé ?
0
Utilisateur anonyme
28 janv. 2021 à 14:32
Qu’est ce que tu appelles récupérer?
0
Quand il est utilisé par un autre processus j'aimerai pourvoir le compresser malgré le fait qu'il sois déjà utilisé
0

Vous n’avez pas trouvé la réponse que vous recherchez ?

Posez votre question
Utilisateur anonyme
29 janv. 2021 à 12:05
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
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
Utilisateur anonyme
30 janv. 2021 à 07:31
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
Pat > Utilisateur anonyme
30 janv. 2021 à 09:42
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
Utilisateur anonyme
31 janv. 2021 à 09:18
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