字符串中的值不正确

时间:2011-11-15 11:08:18

标签: c# string windows-phone-7

我遇到字符串值问题。该字符串是全局声明的。字符串是name_file_image

我有这段代码:

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

我从内存中的文件中读取XML,并且我希望使用XML中存在的名称保存图像。但我有一个问题。变量字符串始终具有相同的名称。我想代码不正确。有什么帮助吗?

1 个答案:

答案 0 :(得分:2)

您正在调用WebClient.OpenReadAsync方法,该方法正在进行他的工作(顾名思义)异步。要解决此问题,您必须使用OpenReadAsync()方法传递文件名。

在您的情况下将是: webClient.OpenReadAsync(new Uri(url_image), name_file_image );

在webClient_image事件处理程序中,您可以从OpenReadCompletedEventArgs参数中提取值。参数e具有一些属性。 e.UserState现在应该包含你的文件名。