创建隐藏文件夹

48

我是否可以在C#中以编程方式创建(并访问)存储设备上的隐藏文件夹?


1
重新标记,因为这不是一个特定于C#语言的问题。 - Jay Bazuzi
5个回答

130
using System.IO; 

string path = @"c:\folders\newfolder"; // or whatever 
if (!Directory.Exists(path)) 
{ 
DirectoryInfo di = Directory.CreateDirectory(path); 
di.Attributes = FileAttributes.Directory | FileAttributes.Hidden; 
}

21
现在,您是谷歌搜索结果的第一名。 - KDecker

30

可以的。像平常一样创建目录,然后只需设置其属性即可。例如:

DirectoryInfo di = new DirectoryInfo(@"C:\SomeDirectory");

//See if directory has hidden flag, if not, make hidden
if ((di.Attributes & FileAttributes.Hidden) != FileAttributes.Hidden)
{   
     //Add Hidden flag    
     di.Attributes |= FileAttributes.Hidden;    
}

3
条件语句可以简化为 if (!di.Attributes.HasFlag(FileAttributes.Hidden)) - schoetbi

7
CreateHiddenFolder(string name)  
{  
  DirectoryInfo di = new DirectoryInfo(name);  
  di.Create();  
  di.Attributes |= FileAttributes.Hidden;  
}  

4
string path = @"c:\folders\newfolder"; // or whatever 
if (!System.IO.Directory.Exists(path)) 
{ 
    DirectoryInfo di = Directory.CreateDirectory(path); 
    di.Attributes = FileAttributes.Directory | FileAttributes.Hidden; 
}

From here.


-2

获取仅根文件夹路径的代码。

例如,如果我们有C:/Test/ C:/Test/Abc C:/Test/xyz C:/Test2/ C:/Test2/mnp

它将返回根文件夹路径,即 C:/Test/ C:/Test2/

            int index = 0;
            while (index < lst.Count)
            {
                My obj = lst[index];
                lst.RemoveAll(a => a.Path.StartsWith(obj.Path));
                lst.Insert(index, obj );
                index++;                    
            }

6
没有解释的代码转储很少有用。请添加一些上下文说明。 (另外,您可能想知道您回答了一个超过6年的帖子...) - Chris

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接