C#对桌面的引用
我正在使用文件流写出一个文件 我希望能够将文件写入桌面 如果我有C#对桌面的引用,c#,C#,我正在使用文件流写出一个文件 我希望能够将文件写入桌面 如果我有 tw = new StreamWriter("NameOflog file.txt"); 我希望能够在文件名前面标识某种@desktop,它将自动插入到桌面的路径。这在C#中存在吗?或者我必须逐个计算机(操作系统逐个操作系统)查看桌面上有什么。快速谷歌搜索揭示了这一点: string strPath = Environment.GetFolderPath( System.Envi
tw = new StreamWriter("NameOflog file.txt");
我希望能够在文件名前面标识某种@desktop,它将自动插入到桌面的路径。这在C#中存在吗?或者我必须逐个计算机(操作系统逐个操作系统)查看桌面上有什么。快速谷歌搜索揭示了这一点:
string strPath = Environment.GetFolderPath(
System.Environment.SpecialFolder.DesktopDirectory);
编辑:这将适用于Windows,但也适用。您要使用,请传入
还有一个SpecialFolder.Desktop
,它表示逻辑桌面位置-但不清楚两者之间的区别。类似于:
Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory))
string logPath = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.Desktop),
"NameOflog file.txt");
tw = new StreamWriter(logPath);
是的。
您可以使用环境变量。
像
但我不建议自动将日志文件写入用户桌面。
您应该将该文件的链接添加到“开始”菜单文件夹中。
甚至在事件日志中填充它们。(好多了)你想要环境。SpecialFolder
string fileName = "NameOflog file.txt";
path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), fileName);
tw = new StreamWriter(path);
我也使用上面提到的方法 但这里有几个不同的选项也很有效(只是为了得到一个更全面的列表): 然后:
天哪,乔恩·斯基特被狠狠揍了一顿。乔恩,你不会在我们面前失去优势吧,伙计我正忙着查找链接:(拜托,Jon,你现在应该已经记住了这些内容:)区别可能与通过组策略重定向文件夹有关。可能SpecialFolder.Desktop指的是文件夹的实际位置,而不是其在硬盘上的正常路径……就像在设置中,您的桌面存储在您的配置文件中,而您的配置文件实际上位于中央服务器上?必须在两者之间加上\\,但这很完美。谢谢,您不需要在stringNote上调用ToString(),根据这一点,它只在Windows上工作,所以对于其他操作系统,您可以先检查它是否工作。@schnaader:我相信它在Mono/Linux上也可以工作(它应该返回“/home/username/desktop”)。@Noldorin:谢谢您的提示,我终于找到了一个关于Mono和Environment.SpecialFolder的链接:
string fileName = "NameOflog file.txt";
path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), fileName);
tw = new StreamWriter(path);
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");