C# 启动外部程序如何限制启动目录为外部程序的目录
时间: 2023-10-12 10:15:15 浏览: 55
您可以使用 `System.Diagnostics.ProcessStartInfo` 类来启动外部程序,并通过设置 `WorkingDirectory` 属性来限制外部程序的启动目录。以下是一个示例代码:
```csharp
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.FileName = "external_program.exe";
startInfo.WorkingDirectory = "D:\\external_program_directory"; // 设置外部程序的启动目录
Process.Start(startInfo);
```
在上面的示例中,我们将 `WorkingDirectory` 属性设置为外部程序所在的目录,这样在启动外部程序时就会限制其启动目录为指定的目录。
相关问题
C# 设置外部程序所在的目录会有文件夹权限问题么
如果您在 C# 中设置外部程序所在的目录,可能会遇到文件夹权限问题。如果您的程序需要在指定目录下创建、修改或删除文件,那么您需要确保当前用户对该目录具有足够的权限。
如果您在 C# 中启动的外部程序需要访问特定的目录,那么您也需要确保当前用户对该目录具有足够的权限。您可以使用 `System.IO.Directory` 类的 `GetAccessControl` 方法来获取指定目录的访问控制列表,然后使用 `System.Security.AccessControl.FileSystemAccessRule` 类来检查当前用户是否具有所需的访问权限。以下是一个示例代码:
```csharp
string path = "D:\\external_program_directory";
DirectorySecurity security = Directory.GetAccessControl(path);
WindowsIdentity identity = WindowsIdentity.GetCurrent();
WindowsPrincipal principal = new WindowsPrincipal(identity);
AuthorizationRuleCollection rules = security.GetAccessRules(true, true, typeof(SecurityIdentifier));
foreach (AuthorizationRule rule in rules)
{
FileSystemAccessRule fsRule = rule as FileSystemAccessRule;
if (fsRule != null && fsRule.IdentityReference.Equals(identity.User) && (fsRule.FileSystemRights & FileSystemRights.Modify) == FileSystemRights.Modify)
{
// 当前用户具有修改目录权限
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.FileName = "external_program.exe";
startInfo.WorkingDirectory = path;
Process.Start(startInfo);
break;
}
}
```
在上面的示例中,我们首先使用 `Directory.GetAccessControl` 方法获取指定目录的访问控制列表,然后使用 `WindowsIdentity.GetCurrent` 方法获取当前用户的标识,最后使用 `WindowsPrincipal` 类来检查当前用户是否具有所需的访问权限。如果当前用户具有修改目录权限,则启动外部程序,并设置其启动目录为指定的目录。
C# 将外部程序设置为后台运行
你可以使用C#中的Process类来将外部程序设置为后台运行。下面是一个示例代码:
```csharp
using System.Diagnostics;
Process process = new Process();
process.StartInfo.FileName = "path/to/your/program.exe";
process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
process.Start();
```
在这个示例中,我们使用Process类来启动外部程序,并将窗口样式设置为隐藏。这样,程序就会在后台运行,而不会显示在屏幕上。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)