글 작성자: 써니루루

자료제공 : http://hugeflow.com/





이전 내용에 Silverlight의 네트워크에 작성한 내용이 있다.

2009/04/30 - [.NET/SilverLight] - Silverlight - Network


이 내용을 바탕으로 다음의 소스코드를 작성하였으므로 내용의 이해가 조금 부족하면 확인하시길...


예제는 프로젝트명 WebClientTest로 하였고,
먼저 Page.xaml 코드는

<UserControl x:Class="WebClientTest.Page"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Width="Auto" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d" d:DesignWidth="500" d:DesignHeight="418">
    <Grid x:Name="LayoutRoot" Background="White">

        <TextBox Height="47" Margin="8,8,100,0" VerticalAlignment="Top" Text="http://hugeflow.com/sample.xml" TextWrapping="Wrap" x:Name="tboxAddress"/>
        <Button HorizontalAlignment="Right" Margin="0,8,8.192,0" VerticalAlignment="Top" Content="Get" Width="88" Height="47" x:Name="buttonGet" Click="buttonGet_Click"/>
        <TextBlock Margin="8,59,8,8" Text="" TextWrapping="Wrap" x:Name="tbOutput"/>

    </Grid>
</UserControl>

 






다음으로 C# 코드

using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;

namespace WebClientTest
{
    public partial class Page : UserControl
    {
        public Page()
        {
            InitializeComponent();
        }

        private void buttonGet_Click(object sender, RoutedEventArgs e)
        {
            if (string.IsNullOrEmpty(tboxAddress.Text) == true)
            {
                return;
            }

            try
            {
                WebClient wc = new WebClient();
                wc.DownloadStringCompleted += new DownloadStringCompletedEventHandler(wc_DownloadStringCompleted);
                wc.DownloadStringAsync(new Uri(tboxAddress.Text, UriKind.Absolute));
            }
            catch (Exception ex)
            {
                tbOutput.Text = ex.Message;
                throw;
            }
        }

        void wc_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            if (e.Cancelled == true)
            {
                tbOutput.Text = "취소되었습니다.";
                return;
            }

            if (e.Error != null)
            {
                if (string.IsNullOrEmpty(e.Error.Message) == false)
                {
                    tbOutput.Text = e.Error.Message;
                }
                else
                {
                    tbOutput.Text = e.Error.ToString();
                }
                return;
            }

            tbOutput.Text = e.Result;
        }
    }
}