c# / 使用 OpenFileDialog 重命名 dll

c# / Rename dll using OpenFileDialog

我的 C# 程序卡住了。所以用户必须按下一个按钮来创建一个随机字符串(工作正常),然后他可以选择单击另一个按钮。这个打开一个文件对话框,让他选择一个他想重命名为随机字符串的 dll 文件。我无法让它工作。它说我的 dll 已经 运行 在另一个进程中(实际上不是)。非常感谢任何帮助:)

private void btnEncrypt_Click_1(object sender, EventArgs e)
    {
        // sets a random string to txtEncrypt.text
    }
private void button1_Click(object sender, EventArgs e)
    {
        OpenFileDialog MyOpenFileDialog = new OpenFileDialog();

        //filedialog
        MyOpenFileDialog.Filter = "dll files (*.dll) |*.dll";//filter
        MyOpenFileDialog.Title = "Chose the dll file";
        MyOpenFileDialog.InitialDirectory = "C:\Users\Gebruiker\Desktop";
        MyOpenFileDialog.FilterIndex = 1;
        MyOpenFileDialog.RestoreDirectory = true;

        //if ok
        if (MyOpenFileDialog.ShowDialog() == DialogResult.OK)
        {
            strPath = MyOpenFileDialog.FileName;
            StreamReader reader = new StreamReader(strPath);

            System.IO.File.Move(strPath, "C:\Users\Gebruiker\Desktop\" + txtEncrypt.Text + ".dll");
        }
        else //cancel
        {
            strPath = null;
        }

这是因为您的 StreamReader 正在打开文件,因此无法移动。该行似乎无论如何都没有做任何事情,因此您可以将其删除。理想情况下将其替换为

if (System.IO.File.Exists(strPath))
{
    System.IO.File.Move(strPath, "C:\Users\Gebruiker\Desktop\" + txtEncrypt.Text + ".dll");
}

只需注释 streem reader 行的初始化或将其移到重命名行旁边,但不要忘记传递新名称