Start MS DOS command "attrib" as process (C#)
I'm trying to hide a folder with C# using the MSDOS "attrib" command.
For now i'm able to do that by writing the "attrib" command + arguments in a batch file, running that file开发者_C百科 using Process.Start()
, and then deleting it. I was wondering, can I do that directly from C#?
Here is what i've tryed so far... (the code below doesen't work)
public static void hideFolder(bool hide, string path)
{
string hideOrShow = (hide) ? "+" : "-";
Process.Start("attrib " + hideOrShow + "h " + hideOrShow + "s \"" + path + "\" /S /D");
}
Any help would be appriciated! Thanx!
What you asked for:
string hideOrShow = (hide) ? "+" : "-";
Process.Start("cmd /c attrib " + hideOrShow + "h " + hideOrShow + "s \"" + path + "\" /S /D");
What you should do instead:
File.SetAttributes(path, FileAttributes.Hidden);
The first parameter to Process.Start() needs to be the name of an executable file or document. You'll need to pass in two parameters, like this:
Process.Start("attrib.exe", hideOrShow + "h " + hideOrShow + "s \"" + path + "\" /S /D");
Also, while attrib.exe will work when called directly, most people will pass this kind of DOS-style command to the command interpreter (which will also work for built-in commands, etc.)
Process.Start("cmd.exe", "/c attrib " + restOfTheArguments);
C# makes this really easy - the idea is you get the files current attributes (File.GetAttributes()), then you add in the Hidden attribute before calling File.SetAttributes()
check the below out, it'll make c:\blah hidden
static void Main(string[] args)
{
FileAttributes oldAttributes = File.GetAttributes(@"c:\blah");
File.SetAttributes(@"c:\blah", oldAttributes | FileAttributes.Hidden);
}
to remove the hidden attribute you need to remove the hidden attribute
static void Main(string[] args)
{
FileAttributes newAttributes = File.GetAttributes(@"c:\blah");
newAttributes = newAttributes & (~FileAttributes.Hidden);
File.SetAttributes(@"c:\blah", newAttributes);
}
What's the error? Why not use http://msdn.microsoft.com/en-us/library/system.io.filesysteminfo.attributes.aspx ?
精彩评论