Question

Dans .Net, nous pouvons retreive les chemins aux « dossiers spéciaux », tels que des documents / bureau, etc. Aujourd'hui, j'ai essayé de trouver un moyen d'obtenir le chemin vers le dossier « Téléchargements », mais il ne suffit pas spéciale il semble.

Je sais que je peux faire juste 'C: \ Users \ Nom d'utilisateur \ Downloads', mais qui semble une solution laid. Alors, comment puis-je retreive le chemin en utilisant .Net?

Était-ce utile?

La solution

Le problème de votre première réponse est qu'il vous donnerait un mauvais résultat si le défaut Téléchargements Dir a été modifiée pour [Download1]! La bonne façon de le faire toutes les possibilités couvrant est

using System;
using System.Runtime.InteropServices;

static class cGetEnvVars_WinExp    {
    [DllImport("Shell32.dll")] private static extern int SHGetKnownFolderPath(
        [MarshalAs(UnmanagedType.LPStruct)]Guid rfid, uint dwFlags, IntPtr hToken,
        out IntPtr ppszPath);

    [Flags] public enum KnownFolderFlags : uint { SimpleIDList = 0x00000100
        , NotParentRelative = 0x00000200, DefaultPath = 0x00000400, Init = 0x00000800
        , NoAlias = 0x00001000, DontUnexpand = 0x00002000, DontVerify = 0x00004000
        , Create = 0x00008000,NoAppcontainerRedirection = 0x00010000, AliasOnly = 0x80000000
    }
    public static string GetPath(string RegStrName, KnownFolderFlags flags, bool defaultUser) {
        IntPtr outPath;
        int result = 
            SHGetKnownFolderPath (
                new Guid(RegStrName), (uint)flags, new IntPtr(defaultUser ? -1 : 0), out outPath
            );
        if (result >= 0)            {
            return Marshal.PtrToStringUni(outPath);
        } else {
            throw new ExternalException("Unable to retrieve the known folder path. It may not "
                + "be available on this system.", result);
        }
    }

}   

Pour le tester, si vous le désirez spécifiquement téléchargement dir personnel, vous défaut drapeau false ->

using System.IO;
class Program    {
    [STAThread]
    static void Main(string[] args)        {
        string path2Downloads = string.Empty;
        path2Downloads = 
            cGetEnvVars_WinExp.GetPath("{374DE290-123F-4565-9164-39C4925E467B}", cGetEnvVars_WinExp.KnownFolderFlags.DontVerify, false);
        string[] files = { "" };
        if (Directory.Exists(path2Downloads)) {
            files = Directory.GetFiles(path2Downloads);
        }
    }//Main
}

Ou juste une Environment.ExpandEnvironmentVariables ligne () -> (la solution la plus simple).

using System.IO;
class Program    {
/* https://ss64.com/nt/syntax-variables.html */
    [STAThread]
    static void Main(string[] args)        {
        string path2Downloads = string.Empty;
        string[] files = { "" };
        path2Downloads = Environment.ExpandEnvironmentVariables(@"%USERPROFILE%\Downloads");
        if (Directory.Exists(path2Downloads)) {
            files = Directory.GetFiles(path2Downloads);
        }
    }//Main
}

Autres conseils

Oui il est spécial, découvrir le nom de ce dossier ne devienne pas possible jusqu'à ce que Vista. .NET doit encore soutenir les systèmes d'exploitation antérieurs. Vous pouvez Pinvoke SHGetKnownFolderPath () pour contourner cette limitation, comme ceci:

using System.Runtime.InteropServices;
...

public static string GetDownloadsPath() {
    if (Environment.OSVersion.Version.Major < 6) throw new NotSupportedException();
    IntPtr pathPtr = IntPtr.Zero;
    try {
        SHGetKnownFolderPath(ref FolderDownloads, 0, IntPtr.Zero, out pathPtr);
        return Marshal.PtrToStringUni(pathPtr);
    }
    finally {
        Marshal.FreeCoTaskMem(pathPtr);
    }
}

private static Guid FolderDownloads = new Guid("374DE290-123F-4565-9164-39C4925E467B");
[DllImport("shell32.dll", CharSet = CharSet.Auto)]
private static extern int SHGetKnownFolderPath(ref Guid id, int flags, IntPtr token, out IntPtr path);

Essayez ceci:

string path = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile)+ @"\Downloads";

J'ai utilisé le code et ci-dessous il fonctionne pour .net 4.6 avec Windows 7 et plus. Le code donne ci-dessous le chemin du dossier de profil de l'utilisateur -> "C:\Users\<username>"

string userProfileFolder = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);

Suivant pour accéder aux téléchargements dossier simplement combiner des chaînes de chemin supplémentaires ci-dessous:

string DownloadsFolder = userProfileFolder + "\\Downloads\\";

Maintenant, le résultat final sera

"C:\Users\<username>\Downloads\"

L'espoir fait gagner du temps pour quelqu'un dans l'avenir.

essayer:

Dim Dd As String = Environment.GetFolderPath(Environment.SpecialFolder.Favorites)
Dim downloD As String = Dd.Replace("Favorites", "Downloads")
txt1.text = downLoD

est juste un truc, pas la solution.

Pour VB, essayez ...

Dim strNewPath As String = IO.Path.GetDirectoryName(Environment.GetFolderPath(Environment.SpecialFolder.Desktop)) + "\Downloads\"
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top