CindyB
January 6, 2009, 12:50am
1
Hello, I’m doing mailmerge with regions using Aspose.Words for .NET, and I’m getting a “WebException occurred” error when calling
builder.InsertImage(imageFileName, width, height);
The specific error is: The remote server returned an error: (404) Not Found.
I need to programmatically return false if the image cannot be found or is not successfully inserted. I’ve tried using a try block and if/else statements with no luck. How can I capture and handle the 404 error?
Thank you in advance!
Hi
Thanks for your request. You can try using the following code:
public void Test064()
{
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
InsertImageFromURL(builder, "http://www.aspose.com/Images/aspose-logo.jpg", 250, 100);
doc.Save(@"Test064\out.doc");
}
private void InsertImageFromURL(DocumentBuilder builder, string url, double width, double height)
{
try
{
//Prepare the web page we will be asking for
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "GET";
request.ContentType = "image/JPEG";
request.UserAgent = "Mozilla/4.0+(compatible;+MSIE+5.01;+Windows+NT+5.0";
//Execute the request
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
//We will read data via the response stream
Stream resStream = response.GetResponseStream();
//Write content into the MemoryStream
BinaryReader resReader = new BinaryReader(resStream);
MemoryStream imgStream = new MemoryStream(resReader.ReadBytes((int)response.ContentLength));
//Insert image into the document
builder.InsertImage(imgStream, width, height);
}
catch (WebException ex)
{
//Handle web exceptions
}
catch (Exception ex)
{
//Handle other exceptions
}
}
You can parse ex.Status. Please see the following link for more information.
https://docs.microsoft.com/en-us/dotnet/api/system.net.webexceptionstatus
Hope this helps.
Best regards.
CindyB
January 7, 2009, 2:33pm
3
Thank you for the quick response and help. The problem was actually a flag set in VS 2005 to throw an error for all CLR exceptions. Turning the flag off thru Debug | Exceptions… allowed me to capture and handle exceptions in the ‘catch’.
Thank you again,
Cindy