Search code examples
c#dllrenameopenfiledialog

Rename dll using OpenFileDialog


I'm stuck with my program in C#. So the user has to press a button to create a random string (working fine) he can then chose to click on the other button. this one opens a FileDialog and let him chose a dll file he wants to rename into the random string. I can't get it working. it says my dll is already running in another process (which is not). Any help is greatly appreciated :)

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;
    }
}

Solution

  • It's because your StreamReader is opening the file so it can't be moved. That line doesn't appear to be doing anything anyway so you can probably remove it. Ideally replace it with

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