如何从我的程序中调用 "net share" 命令?

How can I call the "net share" command from within my program?

我目前正在尝试制作一个使用 CMD 命令 net share 的应用程序。但是,当我按下运行代码的按钮时,出现以下错误:

An unhandled exception of type 'System.ComponentModel.Win32Exception' occurred in System.dll.

这是我使用的代码:

Process cmd = new Process();
cmd.StartInfo.FileName = "net share";
cmd.StartInfo.UseShellExecute = false;
cmd.StartInfo.Arguments = txt_shareName + "=" + path;
cmd.StartInfo.RedirectStandardOutput = true;
cmd.Start();
txt_Logs.Text = cmd.StandardOutput.ReadToEnd();

但是当您将 ipconfig 放入文件名部分并将 /all 放入参数部分时,它会完美地工作。

"net" 这是一个程序和 "share" 参数。试试这个:

cmd.StartInfo.FileName = "net";
cmd.StartInfo.Arguments = "share " + txt_shareName + "=" + path;

问题在于 StartInfo.File,"net share" 不是有效的文件名。

试试这个

Process cmd = new Process()'
cmd.StartInfo.FileName = "net";
cmd.StartInfo.UseShellExecute = false;
cmd.StartInfo.Arguments = "share " + txt_shareName + "=" + path;
cmd.StartInfo.RedirectStandardOutput = true;
cmd.Start();

如果 path 包含空格,则需要用引号引起来。

Process cmd = new Process();
            cmd.StartInfo.FileName = "net";
            cmd.StartInfo.UseShellExecute = false;
            cmd.StartInfo.Arguments = "share";
            cmd.StartInfo.RedirectStandardOutput = true;
            cmd.Start();

net 是 sys32 中的一个 exe..share 是一个参数..将其添加到您的参数中..

这是因为 net share 需要管理员权限才能 运行 此命令。 当您尝试 运行 时,仅 Net Share 它会完美无缺,并且不需要任何特权。但是当你在命令提示符中尝试 运行 带有参数的命令时,它会给出错误说明

System error 5 has occurred.

Access is denied.

因此您需要运行作为管理员

可能的解决方案是您可以 运行 Visual Studio 作为管理员

到 运行 使用 administrator privilege 的命令,而如果 OS 是 Vista 或更高版本,你可以像下面那样做

if (System.Environment.OSVersion.Version.Major >= 6)
{
   p.StartInfo.Verb = "runas";
}

如@Mohit 所述,这是管理员权限的问题。您可以 运行 通过添加以下内容从 C# 以管理员身份进行处理:

cmd.StartInfo.Verb = "runas";