V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
• 请不要在回答技术问题时复制粘贴 AI 生成的内容
life90
V2EX  ›  程序员

这段 C# 代码为啥一直提示文件未找到

  •  
  •   life90 · 2 天前 · 685 次点击

    本来用 Python 实现了一个类似功能,就想着用 Visual Studio C# 能不能实现个,纯属写着好玩。但一直提示这个错误,下断点,我看了值也没问题。故而求助下 V 友

    XAML

    <Window x:Class="bitlockerpatch.MainWindow"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
            xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
            xmlns:local="clr-namespace:bitlockerpatch"
            mc:Ignorable="d"
            Title="BitLocker 天意解锁器" Height="450" Width="800">
        <Grid>
            <Label x:Name="label1" Content="当前驱动器" HorizontalAlignment="Left" Margin="224,54,0,0" VerticalAlignment="Top"/>
            <Label x:Name="label2" Content="生成密码数量" HorizontalAlignment="Left" Margin="224,104,0,0" VerticalAlignment="Top"/>
            <TextBox x:Name="textbox1" HorizontalAlignment="Left" Margin="356,54
                     ,0,0" TextWrapping="Wrap" Text="C" VerticalAlignment="Top" Width="120"/>
            <TextBox x:Name="textbox2" HorizontalAlignment="Left" Margin="356,104
                     ,0,0" TextWrapping="Wrap" Text="1000000" VerticalAlignment="Top" Width="120"/>
            <Button x:Name="unlocked" Content="解锁" HorizontalAlignment="Left" Margin="585,69,0,0" VerticalAlignment="Top" Height="38" Width="81"/>
            <ProgressBar x:Name="ProgressBar" HorizontalAlignment="Center" Height="18" Margin="0,154,0,0" VerticalAlignment="Top" Width="350"/>
            <TextBox x:Name="logbox" HorizontalAlignment="Left" Margin="57,203,0,0" TextWrapping="Wrap" Text="logBox" VerticalAlignment="Top" Width="668" RenderTransformOrigin="0.335,0.696" Height="206"/>
        </Grid>
    
    </Window>
    

    CS

    using System;
    using System.Diagnostics;
    using System.IO;
    using System.Security.Principal;
    using System.Text;
    using System.Threading.Tasks;
    using System.Windows;
    
    namespace bitlockerpatch
    {
        public partial class MainWindow : Window
        {
            private static readonly Random random = new Random();
    
            public MainWindow()
            {
                InitializeComponent();
                this.Loaded += MainWindow_Loaded;
                unlocked.Click += Unlocked_ClickAsync;
            }
    
            private void MainWindow_Loaded(object sender, RoutedEventArgs e)
            {
                if (!IsAdministrator())
                {
                    MessageBox.Show("请以管理员身份运行此程序。", "警告", MessageBoxButton.OK, MessageBoxImage.Warning);
                    //this.Close();
                }
            }
    
            private bool IsAdministrator()
            {
                try
                {
                    WindowsIdentity currentIdentity = WindowsIdentity.GetCurrent();
                    WindowsPrincipal currentPrincipal = new WindowsPrincipal(currentIdentity);
                    return currentPrincipal.IsInRole(WindowsBuiltInRole.Administrator);
                }
                catch (Exception ex)
                {
                    logbox.AppendText($"检查管理员权限时发生错误:{ex.Message}\n");
                    return false;
                }
            }
    
            private async void Unlocked_ClickAsync(object sender, RoutedEventArgs e)
            {
                try
                {
                    // 输入验证
                    if (string.IsNullOrEmpty(textbox1.Text) || textbox1.Text.Length != 1 || !char.IsLetter(textbox1.Text[0]))
                    {
                        logbox.AppendText("请输入有效的驱动器字母(如 C 或 D )。\n");
                        return;
                    }
                    string driveLetter = textbox1.Text.ToUpper();
    
                    if (!int.TryParse(textbox2.Text, out int passwordCount) || passwordCount <= 0)
                    {
                        logbox.AppendText("请输入有效的密码数量(正整数)。\n");
                        return;
                    }
    
                    Dispatcher.Invoke(() =>
                    {
                        logbox.AppendText($"开始解锁驱动器 {driveLetter},尝试 {passwordCount} 个密码...\n");
                        ProgressBar.Value = 0;
                    });
    
                    await Task.Run(() =>
                    {
                        try
                        {
                            StringBuilder logBuffer = new StringBuilder();
                            for (int i = 1; i <= passwordCount; i++)
                            {
                                string recoveryPassword = GenerateRecoveryPassword();
                                bool unlocked = UnlockDrive(driveLetter, recoveryPassword);
    
                                logBuffer.AppendLine($"尝试密码 {i}:{recoveryPassword},结果:{(unlocked ? "成功" : "失败")}");
    
                                if (i % 10 == 0 || i == passwordCount)
                                {
                                    Dispatcher.Invoke(() =>
                                    {
                                        logbox.AppendText(logBuffer.ToString());
                                        logBuffer.Clear();
                                        ProgressBar.Value = (int)(i * 100.0 / passwordCount);
                                    });
                                }
    
                                if (unlocked)
                                {
                                    Dispatcher.Invoke(() =>
                                    {
                                        logbox.AppendText($"成功解锁驱动器 {driveLetter}!\n");
                                    });
                                    return;
                                }
                            }
    
                            Dispatcher.Invoke(() =>
                            {
                                logbox.AppendText($"尝试完所有密码,未能解锁驱动器 {driveLetter}。\n");
                            });
                        }
                        catch (Exception ex)
                        {
                            Dispatcher.Invoke(() =>
                            {
                                logbox.AppendText($"发生未处理的异常:{ex.Message}\n");
                            });
                        }
                    });
                }
                catch (Exception ex)
                {
                    Dispatcher.Invoke(() =>
                    {
                        logbox.AppendText($"发生未处理的异常:{ex.Message}\n");
                    });
                }
            }
    
            private bool UnlockDrive(string driveLetter, string recoveryPassword)
            {
                try
                {
                    // 1. 构建 PowerShell 命令
                    // string powerShellCommand = $"manage-bde -unlock {driveLetter}: -RP {recoveryPassword}";
                    string systemPath = Environment.GetFolderPath(Environment.SpecialFolder.System);
                    string manageBdePath = Path.Combine(systemPath, "powershell.exe");
    
                    ProcessStartInfo startInfo = new ProcessStartInfo
                    {
                        FileName = manageBdePath,
                        Arguments = $" manage-bde -unlock {driveLetter}: -RP {recoveryPassword}",
                        RedirectStandardOutput = true,
                        RedirectStandardError = true,
                        UseShellExecute = false,
                        CreateNoWindow = true
                    };
    
                    using (Process process = new Process { StartInfo = startInfo })
                    {
                        process.Start();
                        process.WaitForExit();
    
                        string output = process.StandardOutput.ReadToEnd();
                        string error = process.StandardError.ReadToEnd();
    
                        // 检查解锁是否成功
                        bool isUnlocked = output.Contains("successfully unlocked"); // 根据实际输出修改判断条件
    
                        // 使用 Dispatcher 更新 UI
                        Dispatcher.Invoke(() =>
                        {
                            if (isUnlocked)
                            {
                                logbox.AppendText($"成功解锁驱动器 {driveLetter}!\n");
                            }
                            else
                            {
                                logbox.AppendText($"manage-bde 输出:{output}\n");
                                logbox.AppendText($"manage-bde 错误:{error}\n");
                            }
                        });
    
                        return isUnlocked; // 返回解锁结果
                    }
                }
                catch (Exception ex)
                {
                    Dispatcher.Invoke(() =>
                    {
                        logbox.AppendText($"解锁时发生错误:{ex.Message}\n");
                    });
                    return false; // 发生异常时返回 false
                }
            }
    
            private string GenerateRecoveryPassword()
            {
                StringBuilder password = new StringBuilder();
                for (int i = 0; i < 8; i++)
                {
                    for (int j = 0; j < 6; j++)
                    {
                        password.Append(random.Next(10));
                    }
                    if (i < 7)
                    {
                        password.Append('-');
                    }
                }
                return password.ToString();
            }
        }
    }
    

    初学者,写得不好还请见谅

    3 条回复    2025-02-20 21:46:15 +08:00
    i8086
        1
    i8086  
       2 天前
    1. Visual Studio Code != Visual Studio
    2. 既然知道异常,为何不把异常贴出来?

    PowerShell 路径问题。代码的路径写着是 C:\WINDOWS\system32\powershell.exe
    ggvoking
        2
    ggvoking  
       2 天前
    +1 路径问题吧,实际 powershell 可不在这个路径,我用下面这个就能调用到
    ProcessStartInfo startInfo = new ProcessStartInfo
    {
    FileName = "powershell",
    Arguments = $"echo hello",
    RedirectStandardOutput = true,
    RedirectStandardError = true,
    UseShellExecute = false,
    CreateNoWindow = true
    };
    life90
        3
    life90  
    OP
       23 小时 4 分钟前
    @i8086 生成 exe 没有异常。只是点击生成后 exe 的解锁按钮会提示找不到文件。

    @ggvoking 在代码可以调用,但是生成的 exe 无法调用。所以很奇怪。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   2733 人在线   最高记录 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 19ms · UTC 12:50 · PVG 20:50 · LAX 04:50 · JFK 07:50
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.