在实际操作中,我们能够通过给客户端呈现"打开文件"的对话框,由客户端自己来选择所想要打开的文件,在这种情况下,你的Silverlight应用程序就可以打开这个指定的文件(并且只能打开这种情况下指定的文件)
本文我们就实践这一功能。
还是如前面的文章所述,我们首先要建立一个新的Silverlight应用程序,我们把它命名为ReadLocal FilesInSL。
Page.xaml文件的代码内容如下:
<
UserControl x:Class
=
"
ReadLocal_FilesInSL.Page
"
xmlns = " http://schemas.microsoft.com/winfx/2006/xaml/presentation "
xmlns:x = " http://schemas.microsoft.com/winfx/2006/xaml "
Width = " 400 " Height = " 400 " >
< Grid x:Name = " LayoutRoot " Background = " DarkBlue " >
< Button x:Name = " btnOpenFile " Content = " Open " BorderThickness = " 2 " BorderBrush = " WhiteSmoke " Background = " Blue " Width = " 75 " Height = " 25 " Click = " btnOpenFile_Click "
VerticalAlignment = " Top " HorizontalAlignment = " Left " Opacity = " 1 " />
< TextBlock x:Name = " Status " Margin = " 0,25,0,0 " Foreground = " White " />
< Image x:Name = " Image " MinWidth = " 200 " MinHeight = " 200 " Margin = " 0,50,0,0 " />
</ Grid >
</ UserControl >
在此代码中,我们建立了一个按钮,当我们点击它时就会跳出打开文件对话框,一个textblock控件用于显示我们所打开的文件的文件名,
xmlns = " http://schemas.microsoft.com/winfx/2006/xaml/presentation "
xmlns:x = " http://schemas.microsoft.com/winfx/2006/xaml "
Width = " 400 " Height = " 400 " >
< Grid x:Name = " LayoutRoot " Background = " DarkBlue " >
< Button x:Name = " btnOpenFile " Content = " Open " BorderThickness = " 2 " BorderBrush = " WhiteSmoke " Background = " Blue " Width = " 75 " Height = " 25 " Click = " btnOpenFile_Click "
VerticalAlignment = " Top " HorizontalAlignment = " Left " Opacity = " 1 " />
< TextBlock x:Name = " Status " Margin = " 0,25,0,0 " Foreground = " White " />
< Image x:Name = " Image " MinWidth = " 200 " MinHeight = " 200 " Margin = " 0,50,0,0 " />
</ Grid >
</ UserControl >
以及一个image控件,用于显示我们所选择的图片文件(在本文我们只打开图片文件)
为了从一个文件中读取内容,我们就需要创建一个“打开文件”对话框,并把它呈现给客户端用户以供他们作出选择。
OpenFileDialog opfdlg
=
new
OpenFileDialog();
opfdlg.Multiselect = false ; // 只允许选择单个文件
opfdlg.Filter = " JPEG Files (*.jpg)|*.jpg " ; // 只允许选择JPG图片文件
bool bResult = ( bool )opfdlg.ShowDialog();
在本处,我们只打开JPEG类型的图片文件,并且限制只能打开一个文件。当然我们可以让用户选择多项文件,也可让他们选择多种类型的文件。
opfdlg.Multiselect = false ; // 只允许选择单个文件
opfdlg.Filter = " JPEG Files (*.jpg)|*.jpg " ; // 只允许选择JPG图片文件
bool bResult = ( bool )opfdlg.ShowDialog();
一旦客户端选择了文件,我们就可以获取关于此文件的有关信息,并读取它的内容。代码如下:
System.IO.FileInfo info
=
opfdlg.File;
Status.Text = info.Name;
System.IO.Stream fs = info.OpenRead();
BitmapImage pics = new BitmapImage();
pics.SetSource(fs);
Image.Source = pics;
fs.Close();
在本例,一旦我打开了指定的文件,图片将会显示在image控件中。
Status.Text = info.Name;
System.IO.Stream fs = info.OpenRead();
BitmapImage pics = new BitmapImage();
pics.SetSource(fs);
Image.Source = pics;
fs.Close();
当然,我们也可以读取诸如text,xml或者binary文件并做相关处理。
Page.xaml完整代码如下:
Code
运行效果图如下:
前往:Silverlight学习笔记清单
本文参照了部分网络资料,希望能够抛砖引玉,大家共同学习。
(转载本文请注明出处)