2009-04-29 18 views
9

Estoy usando una secuencia de archivos para escribir un archivo.C# referencia al escritorio

Tenía la esperanza de poder escribir el archivo en el escritorio.

Si tengo algo así como

tw = new StreamWriter("NameOflog file.txt"); 

Me gustaría ser capaz de tener algún tipo de @Desktop identificado en frente del nombre del archivo que se insertará automáticamente la ruta de acceso al escritorio. ¿Existe esto en C#? O tengo que mirar y ver qué hay en el equipo en una computadora según la computadora (OS por SO).

Respuesta

35

búsqueda rápida de Google revela éste:

string strPath = Environment.GetFolderPath(
         System.Environment.SpecialFolder.DesktopDirectory); 

EDITAR: Esto funciona para Windows, pero Mono supports it, también.

+0

tuvo que añadir \\ entre los dos pero que es Perfecto. Gracias –

+11

No agregue \\ manualmente. Use Path.Combine en su lugar. – OregonGhost

+4

Y no necesita llamar a ToString() en una cadena –

10

Quiere usar Environment.GetFolderPath, pasando SpecialFolder.DesktopDirectory.

También hay SpecialFolder.Desktop que representa lógica ubicación de escritorio - no está claro cuál es la diferencia entre los dos.

+3

Santa vaca, Jon Skeet fue golpeado al golpe.Jon, no estás perdiendo su ventaja sobre nosotros, ¿verdad amigo? :) – TheTXI

+0

Estaba ocupado buscando los enlaces :( –

+2

Vamos Jon, se supone que tienes esto memorizado por ahora :) – TheTXI

1
Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory)) 
7

Algo así como:

string logPath = Path.Combine(
     Environment.GetFolderPath(Environment.SpecialFolder.Desktop), 
     "NameOflog file.txt"); 
    tw = new StreamWriter(logPath); 
+0

+1 ¡Este funciona textualmente! ;-) – Codex

2

sí. puede usar variables ambientales. como

tw = new StreamWriter("%USERPROFILE%\Desktop\mylogfile.txt"); 

pero que no lo recomendaría para escribir automáticamente un archivo de registro en el escritorio de los usuarios. debe agregar el enlace al archivo a la carpeta del menú de inicio. o incluso llenarlos en el registro de eventos. (Mucho mejor)

3

¿Quieres Environment.SpecialFolder

string fileName = "NameOflog file.txt"; 
path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), fileName); 
tw = new StreamWriter(path); 
1

que también utilizan el método mencionado anteriormente.

Pero aquí hay un par de opciones diferentes que funcionan también (sólo para tener una lista más completa):

using System; 
using System.Runtime.InteropServices; 
using System.Text; 

class Program 
{ 
    // 1st way 
    private const int MAX_PATH = 260; 
    private const int CSIDL_DESKTOP = 0x0000; 
    private const int CSIDL_COMMON_DESKTOPDIRECTORY = 0x0019; // Can get to All Users desktop even on .NET 2.0, 
                  // where Environment.SpecialFolder.CommonDesktopDirectory is not available 
    [DllImport("shell32.dll")] 
    private static extern bool SHGetSpecialFolderPath(IntPtr hwndOwner, StringBuilder lpszPath, int nFolder, bool fCreate); 
    static string GetDesktopPath() 
    { 
    StringBuilder currentUserDesktop = new StringBuilder(MAX_PATH); 
    SHGetSpecialFolderPath((IntPtr)0, currentUserDesktop, CSIDL_DESKTOP, false); 
    return currentUserDesktop.ToString(); 
    } 

    // 2nd way 
    static string YetAnotherGetDesktopPath() 
    { 
    Guid PublicDesktop = new Guid("C4AA340D-F20F-4863-AFEF-F87EF2E6BA25"); 
    IntPtr pPath; 

    if (SHGetKnownFolderPath(PublicDesktop, 0, IntPtr.Zero, out pPath) == 0) 
    { 
     return System.Runtime.InteropServices.Marshal.PtrToStringUni(pPath); 
    } 

    return string.Empty; 
    } 
} 

continuación:

string fileName = Path.Combine(GetDesktopPath(), "NameOfLogFile.txt"); 
Cuestiones relacionadas