Domanda

In Net possiamo prelevare i percorsi a 'cartelle speciali', come Documenti / Desktop ecc Oggi ho cercato di trovare un modo per ottenere il percorso della cartella 'Downloads', ma non è abbastanza speciale sembra.

so che posso solo fare 'C: \ Utenti \ nomeutente \ Downloads', ma che sembra una soluzione brutto. Così come posso prelevare il percorso utilizzando .Net?

È stato utile?

Soluzione

Il problema della tua prima risposta è che darebbe risultato sbagliato se l'impostazione predefinita Download Dir è stato modificato in [Download1]! Il modo corretto per farlo che copre tutte le possibilità è

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);
        }
    }

}   

Per provarlo, se si desidera specificamente il download dir personale, è la bandiera di default a 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
}

o solo uno Environment.ExpandEnvironmentVariables linea () -> (la soluzione più semplice).

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
}

Altri suggerimenti

Si è speciale, scoprendo il nome di questa cartella non è diventato possibile fino a Vista. NET deve ancora sostenere sistemi operativi precedenti. È possibile PInvoke SHGetKnownFolderPath () per bypassare questa limitazione, in questo modo:

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);

Prova questo:

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

Ho usato il codice qui sotto e funziona per NET 4.6 con Windows 7 e superiori. Il sotto il codice dà il percorso della cartella del profilo utente -> "C:\Users\<username>"

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

Avanti per accedere ai download cartella nello stesso uniscono le stringhe di percorso aggiuntive, come di seguito:

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

Ora, il risultato finale sarà

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

La speranza fa risparmiare tempo per qualcuno in futuro.

provare:

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

il suo solo un trucco, non è la soluzione.

Per VB, provare ...

Dim strNewPath As String = IO.Path.GetDirectoryName(Environment.GetFolderPath(Environment.SpecialFolder.Desktop)) + "\Downloads\"
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top