Why i'm getting ArgumentException when trying to save a bitmap to the hard disk ? RRS feed

  • Question

  • int imagescount = 0;
            private void SaveImageFromWebBrowser()
                IHTMLDocument2 doc = (IHTMLDocument2)webBrowser1.Document.DomDocument;
                IHTMLControlRange imgRange = (IHTMLControlRange)((HTMLBody)doc.body).createControlRange();
                foreach (IHTMLImgElement img in doc.images)
                    imgRange.execCommand("Copy", false, null);
                    using (Bitmap bmp = (Bitmap)Clipboard.GetDataObject().GetData(DataFormats.Bitmap))
                        bmp.Save(@"e:\webbrowserimages\wbImage" + img.nameProp + imagescount.ToString("D6") + ".bmp",

    The exception is on the line:

    bmp.Save(@"e:\webbrowserimages\wbImage" + img.nameProp + imagescount.ToString("D6") + ".bmp",

    ArgumentException: Illegal characters in path.

    The full exception message:

    System.ArgumentException was unhandled by user code
          Message=Illegal characters in path.
               at System.IO.Path.CheckInvalidPathChars(String path, Boolean checkAdditional)
               at System.Security.Permissions.FileIOPermission.AddPathList(FileIOPermissionAccess access, AccessControlActions control, String[] pathListOrig, Boolean checkForDuplicates, Boolean needFullPath, Boolean copyPathList)
               at System.IO.Path.GetFullPath(String path)
               at System.Drawing.IntSecurity.UnsafeGetFullPath(String fileName)
               at System.Drawing.IntSecurity.DemandWriteFileIO(String fileName)
               at System.Drawing.Image.Save(String filename, ImageCodecInfo encoder, EncoderParameters encoderParams)
               at test.Form1.SaveImageFromWebBrowser() in e:\C-Drive-Backup\Temp\test\Form1.cs:line 812
               at test.Form1.webBrowser1_DocumentCompleted_1(Object sender, WebBrowserDocumentCompletedEventArgs e) in e:\C-Drive-Backup\Temp\test\Form1.cs:line 780

    Saturday, May 23, 2015 9:26 PM


  • ArgumentException: Illegal characters in path.

    Usually, this exception throws when incorrect file path used such as containing illegal characters or unprinted characters etc...

    try to check the value of img.nameProp what dose it contain this is the first step you need to do

    you can use this method to check if the file name is valid or not

    bool IsValidFilename(string testName)
        Regex containsABadCharacter = new Regex("["
              + Regex.Escape(new string(System.IO.Path.GetInvalidPathChars())) + "]");
        if (containsABadCharacter.IsMatch(testName) { return false; };
        return true;

    If this answer was helpful please remember to close your threads by marking helpful posts as answer


    • Edited by Fares amr Saturday, May 23, 2015 9:46 PM
    • Marked as answer by Chocolade1972 Saturday, May 23, 2015 11:04 PM
    Saturday, May 23, 2015 9:40 PM