You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C# Windows服务运行wsl.exe报错求助:系统无法访问文件

问题描述

用C#写的Windows服务里执行wsl.exe运行Linux命令,日志一直报The file cannot be accessed by the system.。不管用LocalSystem账户还是个人账户安装运行服务都没用,但在IDE里用同一个个人账户跑代码完全正常。就算指定了wsl.exe的完整路径,问题还是存在。

服务运行代码如下:

var process = new Process
{
    StartInfo = new ProcessStartInfo
    {
        FileName = "wsl.exe",
        Arguments = "ls",
        RedirectStandardOutput = true,
        RedirectStandardError = true,
        UseShellExecute = false,
        CreateNoWindow = true,
    }
};

process.OutputDataReceived += (sender, e) =>
{
    if (e.Data != null)
    {
        _logger.LogInformation($"Output received: {e.Data}");
    }
};

process.ErrorDataReceived += (sender, e) =>
{
    if (e.Data != null)
    {
        _logger.LogError($"Error received: {e.Data}");
    }
};
process.Exited += (sender, e) =>
{
    _logger.LogInformation($"Process exited with code: {process.ExitCode}");
};
process.Start();
process.BeginOutputReadLine();
process.BeginErrorReadLine();
process.WaitForExit();
解决方案
  • 明确指定wsl.exe完整路径,匹配系统位数
    服务环境下直接写wsl.exe可能解析不到正确路径,尤其是32位程序跑在64位系统上时。直接写绝对路径:

    • 64位系统+64位程序:FileName = @"C:\Windows\System32\wsl.exe"
    • 32位程序跑在64位系统:FileName = @"C:\Windows\SysWOW64\wsl.exe"
  • 调整进程启动参数,补充工作目录
    服务的运行上下文没有交互式登录的环境变量,可设置工作目录为用户目录,同时检查ShellExecute配置:

    StartInfo = new ProcessStartInfo
    {
        FileName = @"C:\Windows\System32\wsl.exe",
        Arguments = "ls",
        RedirectStandardOutput = true,
        RedirectStandardError = true,
        UseShellExecute = false,
        CreateNoWindow = true,
        WorkingDirectory = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile)
    }
    

    如果不需要重定向输出,可将UseShellExecute设为true,让系统帮你处理环境变量加载。

  • 确保服务登录账户完成WSL初始化
    即使用自己的账户跑服务,服务的运行上下文和你手动登录系统的上下文不一样。手动登录该账户,打开一次WSL终端,完成发行版的初始化和配置,确保账户有权限访问WSL相关文件。

  • 添加启动延迟或重试逻辑
    服务刚启动时系统资源可能没完全就绪,可在启动进程前加个1-2秒的延迟,或者进程启动失败时重试1次。

内容的提问来源于stack exchange,提问作者Tiklyt

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 21:13:13