在silverlight中读写文件
首先打开属性,选中允许在浏览器外允许应用程序,然后点击“浏览器外设置”,最后选中“在浏览器之外允许时需要提升的信任”,窗口样式选择”无边框圆角“如图:
XAML代码:
<Grid x:Name="LayoutRoot" Width="695">
<Grid.Background>
<LinearGradientBrush EndPoint="1,0.5" StartPoint="0,0.5">
<GradientStop Color="Black" Offset="1" />
<GradientStop Color="White" Offset="0.785" />
</LinearGradientBrush>
</Grid.Background>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="115" />
</Grid.ColumnDefinitions>
<Border>
<StackPanel Orientation="Vertical" Grid.Column="0" Background="Transparent">
<RichTextBox Name="rtbContent" Height="405" ScrollViewer.VerticalScrollBarVisibility="Auto" ScrollViewer.HorizontalScrollBarVisibility="Auto" >
</RichTextBox>
</StackPanel>
</Border>
<Border Grid.Column="1">
<StackPanel Orientation="Vertical" >
<StackPanel Orientation="Vertical" Height="20">
<Image Name="imgClose" Width="20" Height="20" HorizontalAlignment="Right" MouseLeftButtonDown="imgClose_MouseLeftButtonDown" Source="/ReadingWritingFilesSrc;component/Image/close.png"></Image>
</StackPanel>
<Button Content="Read File" Name="btnReadFile" Width="100" Height="20" Margin="0,160,0,0" Click="ReadFileFromLocalDrive"></Button>
<Button Content="Write File" Name="btnWriteFile" Width="100" Height="20" Margin="0,30,0,0" Click="WriteFileToLocalDrive"></Button>
</StackPanel>
</Border>
</Grid>
CS代码:
<span style="font-size: 12px;">using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Windows; using System.Windows.Controls; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Shapes; using System.IO; namespace ReadingWritingFilesSrc { public partial class MainPage : UserControl { StreamReader fileReader = null; StreamWriter fileWriter = null; public MainPage() { InitializeComponent(); } private void imgClose_MouseLeftButtonDown(object sender, MouseButtonEventArgs e) { Application.Current.MainWindow.Close(); } private void ReadFileFromLocalDrive(object sender, RoutedEventArgs e) { OpenFileDialog ofd = new OpenFileDialog(); ofd.Filter = "Text Files|*.txt"; ofd.Multiselect = false; if (ofd.ShowDialog() == true) { using (fileReader = new StreamReader(ofd.File.OpenRead(), System.Text.Encoding.UTF8)) { rtbContent.Selection.Text = fileReader.ReadToEnd(); } } } private void WriteFileToLocalDrive(object sender, RoutedEventArgs e) { SaveFileDialog sfd = new SaveFileDialog(); sfd.Filter = "Text files|*.txt"; if (sfd.ShowDialog() == true) { using (fileWriter = new StreamWriter(sfd.OpenFile(),System.Text.Encoding.UTF8)) { rtbContent.SelectAll(); fileWriter.Write(rtbContent.Selection.Text); } } } } } </span>
效果图: