2009-04-29 13 views
9

ファイルストリームを使用してファイルを書き出しています。C#デスクトップへの参照

ファイルをデスクトップに書き込めるようにしたいと考えていました。私は、自動的にデスクトップへのパスを挿入するファイル名の前に特定され@desktopのいくつかの並べ替えを持ってできるようにしたいと思い

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

のようなものを持っている場合は

。これはC#に存在しますか?または、デスクトップがコンピュータ(OSによるOS)ベースでコンピュータ上に何であるかを見て調べる必要がありますか?

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

はEDIT::これは、あまりにも、Windowsのために働くが、Mono supports itます

答えて

35

クイックGoogle検索では、このいずれかを明らかにする。

+0

は、両者の間\\追加する必要がありましたが、それはあります完璧。ありがとう –

+11

\\を手動で追加しないでください。代わりにPath.Combineを使用します。 – OregonGhost

+4

そして、文字列にToString()を呼び出す必要はありません –

10

Environment.GetFolderPathを使用して、SpecialFolder.DesktopDirectoryを使用します。

SpecialFolder.Desktop論理のデスクトップの場所を表します.2つの違いが何であるかはっきりしません。

+3

聖なる牛、ジョン・スケートはパンチに打たれました。ジョン、あなたは私たちの上にあなたのエッジを失うことはありません、お友達ですか? :) – TheTXI

+0

私はリンクを捜して忙しかった:( –

+2

ジョンに来て、あなたはこれで今記憶されているものを持っているはずです:) – TheTXI

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

のような何か:

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

+1この1つはそのまま使うことができます! ;-) – Codex

2

うん。 環境変数を使用できます。

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

よう しかし、私は、自動的にユーザーのデスクトップにログファイルを書き込むことはお勧めしません。 ファイルへのリンクをスタートメニューフォルダに追加する必要があります。 を入力したり、イベントログに入力したりすることもできます。 (はるか)

3

あなたはEnvironment.SpecialFolderが

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

私はまた、上記の方法を使用します。

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

その後:ここ

しかし、あまりにも働く夫婦の異なるオプションが(ちょうどより包括的なリストを持っている)です

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