如何访问"Documents and Settings"文件夹?

Yon*_*Nir 6 c# path getfiles access-denied

我在VS 2010中使用C#.NET 4.

当迭代某些路径时,我正在运行这一行:

files = Directory.GetFiles(path, searchPattern);
Run Code Online (Sandbox Code Playgroud)

当路径是文档和设置文件夹时,我得到一个例外.我该如何访问它?不,我不想跳过文件夹试试并抓住.我希望能以某种方式访问​​它.

编辑:我有一个跟进问题.正如我告诉过你的那样,我正在迭代这些路径.有没有办法使用Environment.GetFolderPath但不知何故根据我正在检查的路径识别正确的特殊文件夹?

Sar*_*nan 8

你必须这样使用

var mydocumentsPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
Run Code Online (Sandbox Code Playgroud)

要访问该MyDocuments文件夹.


Son*_*nül 5

Environment.SpecialFolder

系统特殊文件夹是程序文件,程序,系统或启动等文件夹,其中包含公共信息.在安装Windows版本时,系统默认设置特殊文件夹,或由用户显式设置.

GetFolderPath方法返回与此枚举关联的位置.这些文件夹的位置在不同的操作系统上可以具有不同的值,用户可以更改某些位置,并且位置是本地化的.

只是用

string path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
files = Directory.GetFiles(path, searchPattern);
Run Code Online (Sandbox Code Playgroud)

在我的电脑中,它返回为 C:\Users\Soner\Documents

有没有办法使用Environment.GetFolderPath,但根据我正在检查的路径以某种方式识别正确的speical文件夹?

由于SpecialFolder是枚举类型,您可以在循环中迭代它们的值.这是它的样子;

public enum SpecialFolder
{
    AdminTools = 0x30,
    ApplicationData = 0x1a,
    CDBurning = 0x3b,
    CommonAdminTools = 0x2f,
    CommonApplicationData = 0x23,
    CommonDesktopDirectory = 0x19,
    CommonDocuments = 0x2e,
    CommonMusic = 0x35,
    CommonOemLinks = 0x3a,
    CommonPictures = 0x36,
    CommonProgramFiles = 0x2b,
    CommonProgramFilesX86 = 0x2c,
    CommonPrograms = 0x17,
    CommonStartMenu = 0x16,
    CommonStartup = 0x18,
    CommonTemplates = 0x2d,
    CommonVideos = 0x37,
    Cookies = 0x21,
    Desktop = 0,
    DesktopDirectory = 0x10,
    Favorites = 6,
    Fonts = 20,
    History = 0x22,
    InternetCache = 0x20,
    LocalApplicationData = 0x1c,
    LocalizedResources = 0x39,
    MyComputer = 0x11,
    MyDocuments = 5,
    MyMusic = 13,
    MyPictures = 0x27,
    MyVideos = 14,
    NetworkShortcuts = 0x13,
    Personal = 5,
    PrinterShortcuts = 0x1b,
    ProgramFiles = 0x26,
    ProgramFilesX86 = 0x2a,
    Programs = 2,
    Recent = 8,
    Resources = 0x38,
    SendTo = 9,
    StartMenu = 11,
    Startup = 7,
    System = 0x25,
    SystemX86 = 0x29,
    Templates = 0x15,
    UserProfile = 40,
    Windows = 0x24
}
Run Code Online (Sandbox Code Playgroud)