I have a problem with a string value. The string is globally declared. The string is name_file_image.
I have this code:
// iterate image files
foreach (XElement node in xml.Element("graphics").Elements("file"))
{
// pick image
if (node.Attribute("type").Value == "image")
{
// demoing that we found something
//MessageBox.Show(node.Element("fileurl").Value);
string url_image = node.Element("fileurl").Value;
string[] array = url_image.Split('/');
**name_file_image** = array[array.Length - 1];
//MessageBox.Show(**name_file_image**);
WebClient webClient = new WebClient();
webClient.OpenReadCompleted += new OpenReadCompletedEventHandler(webClient_image);
webClient.OpenReadAsync(new Uri(url_image));
}
}
void webClient_image(object sender, OpenReadCompletedEventArgs e)
{
try
{
if (e.Result != null)
{
// Save image to Isolated Storage
// Create virtual store and file stream. Check for duplicate JPEG files.
using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
if (myIsolatedStorage.FileExists(**name_file_image**))
{
myIsolatedStorage.DeleteFile(**name_file_image**);
}
IsolatedStorageFileStream fileStream = new IsolatedStorageFileStream(name_file_image, FileMode.Create, myIsolatedStorage);
BitmapImage bitmap = new BitmapImage();
bitmap.SetSource(e.Result);
WriteableBitmap wb = new WriteableBitmap(bitmap);
wb.SaveJpeg(fileStream, wb.PixelWidth, wb.PixelHeight, 0, 85);
fileStream.Close();
//MessageBox.Show(name_file_image);
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
I read the XML from a file in memory and I want to save the images with the name present in the XML. But I have a problem. The variable string always has the same name. I suppose the code is not correct. Any help?
You’re calling the WebClient.OpenReadAsync method, which is doing his work (as the name suggests) asynchronous. To fix this issue, you have to pass the filename with the OpenReadAsync() method.
In your case that will be:
webClient.OpenReadAsync(new Uri(url_image), name_file_image);
In your webClient_image eventhandler you can than extract the value from the OpenReadCompletedEventArgs parameter. The parameter e has a few properties. e.UserState should now contain your filename.