IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

C# Discussion :

Erreur WebClient Permissions


Sujet :

C#

Vue hybride

Message précédent Message précédent   Message suivant Message suivant
  1. #1
    Membre averti
    Homme Profil pro
    Développeur informatique
    Inscrit en
    Mars 2023
    Messages
    35
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Rhône (Rhône Alpes)

    Informations professionnelles :
    Activité : Développeur informatique

    Informations forums :
    Inscription : Mars 2023
    Messages : 35
    Par défaut Erreur WebClient Permissions
    Bonjour,

    Lorsque j'essaie de télécharger un fichier avec la classe WebClient, j'obtiens cette erreur :

    L'exception System.Net.WebException n'a pas été gérée
    Message=Une exception s'est produite lors d'une demande WebClient.
    Source=System
    StackTrace:
    à System.Net.WebClient.DownloadFile(Uri address, String fileName)
    à System.Net.WebClient.DownloadFile(String address, String fileName)
    à PrepareDocForExternalUse.Program.Main(String[] args)
    à System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args)
    à System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
    à Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
    à System.Threading.ThreadHelper.ThreadStart_Context(Object state)
    à System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
    à System.Threading.ThreadHelper.ThreadStart()
    InnerException: System.IO.DirectoryNotFoundException
    Message=Impossible de trouver une partie du chemin d'accès 'C:\PiecesJointes\'.
    Source=mscorlib
    StackTrace:
    à System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
    à System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy)
    à System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access)
    à System.Net.WebClient.DownloadFile(Uri address, String fileName)
    InnerException:




    Voici mon code :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    using System;
    using System.IO;
    using System.Net;
    using System.Text;
    using System.Text.RegularExpressions;
    using ICSharpCode.SharpZipLib.Core;
    using ICSharpCode.SharpZipLib.Zip;
     
    namespace PrepareDocForExternalUse
    {
        class Program
        {
            static void Main(string[] args)
            {
                // Demande à l'utilisateur le chemin absolu d'un fichier ODT
                Console.WriteLine("Merci de renseigner le chemin absolu d'un fichier ODT:");
                string odtFilePath = Console.ReadLine();
     
                // Lis le contenu du fichier ODT
                byte[] content = File.ReadAllBytes(odtFilePath);
                MemoryStream ms = new MemoryStream();
                ms.Write(content, 0, content.Length);
                ZipFile zf = new ZipFile(ms);
                zf.UseZip64 = UseZip64.Off;
                zf.IsStreamOwner = false;
                ZipEntry entry = zf.GetEntry("content.xml");
                Stream s = zf.GetInputStream(entry);
     
                // Convertit le stream en string
                StreamReader reader = new StreamReader(s);
                string contentXml = reader.ReadToEnd();
     
                // Recherche tous les liens qui commencent par "applnet.test.fr"
                string pattern = @"http://applnet\.test\.fr/GetContenu/Download\.aspx\?p1=.*?;p2=.*?;p5=.*?;p6=NOPUB";
                Regex regex = new Regex(pattern);
                MatchCollection matches = regex.Matches(contentXml);
                // Traite chaque lien trouvé
                foreach (Match match in matches)
                {
                    string link = match.Value;
     
                    string[] parts = link.Split(new string[] { "aspx?" }, StringSplitOptions.None);
                    string queryString = parts[parts.Length - 1];
     
     
     
                    string[] parameterParts = Regex.Split(link, "(?<=aspx\\?)");
     
                    // Télécharge le document intranet correspondant
                    string newFileName = Path.GetFileName(new Uri(link).LocalPath);
                    string folderName = Path.GetFileNameWithoutExtension(odtFilePath);
                    string subFolderName = "PJ - " + folderName;
                    string localFilePath = "C:/PiecesJointes/";
                    string onlineFilePath = "https://com.test.fr/files/test/test/" + queryString;
     
     
                    Directory.CreateDirectory(Path.GetDirectoryName(localFilePath));
     
                    using (WebClient client = new WebClient())
                    {
                        client.DownloadFile(link, localFilePath);
                    }
     
                    // Remplace le lien par le chemin du document téléchargé
                    string newLink = localFilePath.Replace("\\", "/");
                    contentXml = contentXml.Replace(link, newLink);
                }
     
                // Met à jour le content.xml dans le fichier ZIP initial
                byte[] contentXmlBytes = System.Text.Encoding.UTF8.GetBytes(contentXml);
                ms = new MemoryStream();
                zf.BeginUpdate();
     
                // Ajoute le contenu mis à jour au fichier ZIP
                ZipOutputStream zos = new ZipOutputStream(ms);
                zos.UseZip64 = UseZip64.Off;
                zos.IsStreamOwner = false;
     
                // Ajoute l'entrée pour le fichier content.xml
                zos.PutNextEntry(new ZipEntry(entry.Name));
                StreamUtils.Copy(new MemoryStream(contentXmlBytes), zos, new byte[4096]);
     
                // Traite chaque entrée du fichier ODT original
                foreach (ZipEntry origEntry in zf)
                {
                    // Ignore l'entrée pour le fichier content.xml car il a déjà été ajouté
                    if (origEntry.Name == entry.Name) continue;
     
                    // Ajoute l'entrée au nouveau fichier ZIP
                    zos.PutNextEntry(new ZipEntry(origEntry.Name));
                    StreamUtils.Copy(zf.GetInputStream(origEntry), zos, new byte[4096]);
                }
     
                zos.Close();
     
                // Termine la mise à jour du fichier ZIP
                zf.CommitUpdate();
                zf.Close();
     
     
                // Renomme et enregistre le fichier ODT mis à jour
                string updatedFilePath = Path.Combine(Path.GetDirectoryName(odtFilePath), "updated_" + Path.GetFileName(odtFilePath));
                using (FileStream stream = new FileStream(updatedFilePath, FileMode.Create))
                {
                    ms.Position = 0;
                    ms.WriteTo(stream);
                }
                Console.WriteLine("Le fichier ODT a été mis à jour avec succès et enregistré sous le nom : " + updatedFilePath);
     
                Console.ReadLine();
            }
        }
    }

    Apparemment je n'aurai pas les privilèges nécessaires pour écrire à l'emplacement ciblé mais je suis administrateur de mon poste et je suis allé vérifier les propriétés du dossier où je veux stocker les fichiers et je vois bien que j'ai accès à la lecture et à l'écriture.

    Cela pourrait-il venir de mon code ou uniquement de l'ordinateur ? (C'est un ordinateur d'entreprise)

  2. #2
    Membre Expert
    Profil pro
    Inscrit en
    Septembre 2010
    Messages
    1 545
    Détails du profil
    Informations personnelles :
    Âge : 46
    Localisation : France

    Informations forums :
    Inscription : Septembre 2010
    Messages : 1 545
    Par défaut
    Il faut préciser le nom du fichier local sous lequel tu veux enregistrer le fichier téléchargé. Autrement dit, dans client.Download(), le 1er correspond à l'adresse de téléchargement du fichier et le second au nom du fichier sur le pc (il ne faut pas qu'un chemin)
    donc dans ton cas, quelque chose comme
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    client.DownloadFile(link, localFilePath + newFileName);

  3. #3
    Membre averti
    Homme Profil pro
    Développeur informatique
    Inscrit en
    Mars 2023
    Messages
    35
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Rhône (Rhône Alpes)

    Informations professionnelles :
    Activité : Développeur informatique

    Informations forums :
    Inscription : Mars 2023
    Messages : 35
    Par défaut
    Citation Envoyé par umfred Voir le message
    Il faut préciser le nom du fichier local sous lequel tu veux enregistrer le fichier téléchargé. Autrement dit, dans client.Download(), le 1er correspond à l'adresse de téléchargement du fichier et le second au nom du fichier sur le pc (il ne faut pas qu'un chemin)
    donc dans ton cas, quelque chose comme
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    client.DownloadFile(link, localFilePath + newFileName);
    Je te remercie énormément, ça fonctionne parfaitement maintenant

+ Répondre à la discussion
Cette discussion est résolue.

Discussions similaires

  1. Erreur 70: permission denied
    Par ted08 dans le forum VBScript
    Réponses: 6
    Dernier message: 22/12/2008, 10h20
  2. [Upload] Upload de fichier - Erreur de permission
    Par st4nfield dans le forum Langage
    Réponses: 7
    Dernier message: 05/11/2008, 15h26
  3. Réponses: 2
    Dernier message: 07/03/2008, 10h31
  4. Erreur JScript : permission denied
    Par luimême dans le forum Général JavaScript
    Réponses: 7
    Dernier message: 28/12/2007, 12h18
  5. Apllication Visual Studio 2005 : Erreur de permission
    Par Nicolas2812 dans le forum Visual C++
    Réponses: 3
    Dernier message: 01/03/2007, 19h03

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo