Search code examples
c#winformsfolderbrowserdialog

Getting an exception as "The parameter is incorrect.\r\n" while moving file


I have written a code to move a file as follows

            private void Move_Click(object sender, EventArgs e)
    {
        string strOrgpath = string.Empty, strNewpath = string.Empty;
        strOrgpath = tvwACH.SelectedNode.ToString();
        string strPath = strOrgpath.Substring(10);
        FolderBrowserDialog folderborwser1 = new FolderBrowserDialog();

       if (folderborwser1.ShowDialog() == DialogResult.OK)
        {
            try
            {
                strNewpath = folderborwser1.SelectedPath;
                File.Move(strPath, strNewpath);
            }
            catch (Exception ex)
            {

            }
        }

    }

But i am getting the exception as i mentioned can any one tell why and some times i am getting the error as access to the path is denied


Solution

  • Make sure your substring call returns the correct result. If possible, use static methods from the Path class instead. Take a look at the MSDN page for File.Move and pay attention to what parameters are expected -- you should provide two valid full file names (e.g. C:\Blah\myFile.txt).

    "Access denied" error message might happen if the user picks a folder they don't have write access to in the folder browser dialog. That's a scenario you'll have to handle in your code, perhaps by catching the UnauthorizedAccessException.

    Update: the destination file should also point to a filename. So you'll need to do something like this:

    var origFileName = Path.GetFileName(strPath);
    strNewpath = Path.Combine(folderborwser1.SelectedPath, origFileName);
    File.Move(strPath, strNewpath);