启动MS DOS命令" attribute "作为进程(c#)

本文关键字:quot 进程 DOS MS 启动 attribute 命令 | 更新日期: 2023-09-27 17:54:23

我想用MSDOS的" attribute "命令隐藏一个c#文件夹。

现在我可以通过在批处理文件中编写"attrib"命令+参数,使用Process.Start()运行该文件,然后删除它来做到这一点。我想知道,我可以直接从c#做到这一点吗?

这是我到目前为止所尝试的…(下面的代码不起作用)

    public static void hideFolder(bool hide, string path)
    {
        string hideOrShow = (hide) ? "+" : "-";
        Process.Start("attrib " + hideOrShow + "h " + hideOrShow + "s '"" + path + "'" /S /D");
    }

任何帮助将不胜感激!谢谢!

启动MS DOS命令" attribute "作为进程(c#)

您的要求:

string hideOrShow = (hide) ? "+" : "-";
Process.Start("cmd /c attrib " + hideOrShow + "h " + hideOrShow + "s '"" + path + "'" /S /D");

你应该怎么做:

File.SetAttributes(path, FileAttributes.Hidden);

Process.Start()的第一个参数需要是可执行文件或文档的名称。您需要传入两个参数,像这样:

Process.Start("attrib.exe", hideOrShow + "h " + hideOrShow + "s '"" + path + "'" /S /D");

另外,虽然直接调用attrib.exe时可以工作,但大多数人会将这种dos风格的命令传递给命令解释器(也可以用于内置命令等)

Process.Start("cmd.exe", "/c attrib " + restOfTheArguments);

c#使这变得非常简单-其思想是您获得文件的当前属性(File.GetAttributes()),然后在调用File.SetAttributes()之前添加隐藏属性

检查下面,它将使c:'blah hidden

static void Main(string[] args)
{
    FileAttributes oldAttributes = File.GetAttributes(@"c:'blah");
    File.SetAttributes(@"c:'blah", oldAttributes | FileAttributes.Hidden);
}

要移除隐藏属性你需要移除隐藏属性

static void Main(string[] args)
{
    FileAttributes newAttributes = File.GetAttributes(@"c:'blah");
    newAttributes = newAttributes & (~FileAttributes.Hidden);
    File.SetAttributes(@"c:'blah", newAttributes);
}

错误是什么?为什么不用http://msdn.microsoft.com/en-us/library/system.io.filesysteminfo.attributes.aspx呢?