Silverlight 3 – Open, Edit and Save a Text File to a Location outside the Isolated Storage

Posted by: Suprotim Agarwal , on 2/2/2010, in Category Silverlight 2, 3, 4 and 5
Views: 32798
Abstract: In this article, we will see how to Open, Edit and Save a Text File to a Location outside the Isolated Storage
Silverlight 3 – Open, Edit and Save a Text File to a Location outside the Isolated Storage
 
I see a lot of question on the forums asking how to edit text files kept on their machine and then save these files back to a desired location using Silverlight. In Silverlight 2, you had to use the Isolated Storage to save a file locally on the user’s machine. The SaveFileDialog is a new dialog control in Silverlight 3 which allows the user to specify a file name and location to save a file. This control can be invoked only through a user interaction. Let us a see a simple demonstration of using the OpenFileDialog and the SaveFileDialog control.
Create a simple user interface consisting of a TextBox and a Button. The user will first click on the Open button to open a local file and display the text in a TextBox control. After editing the text, the user will be presented the SaveFileDialog control where the user can specify the file name and location and persist the changes.
<UserControl x:Class="SilverlightSaveFileDialog.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d" d:DesignWidth="640" d:DesignHeight="480">
    <Canvas>
        <TextBox Name="txt" Canvas.Left="20" Canvas.Top="50" Width="150" Height="200"
        AcceptsReturn="True"></TextBox>
        <Button Name="btnOpen" Canvas.Left="20" Canvas.Top="270" Click="btnOpen_Click" Content="Open" ></Button>
        <Button Name="btnSave" Canvas.Left="60" Canvas.Top="270" Click="btnSave_Click" Content="Save" ></Button>
    </Canvas>
</UserControl>
Let us first code the btnOpen_click event to read data from a text file and then display it in a textbox.
C#
private void btnOpen_Click(object sender, RoutedEventArgs e)
{
    OpenFileDialog ofd = new OpenFileDialog();
    ofd.Filter = "Text Files|*.txt";
    ofd.FilterIndex = 1;         
 
    if (true == ofd.ShowDialog())
    {
        FileInfo info = ofd.File;
        using (StreamReader sread = info.OpenText())
        {
            txt.Text = sread.ReadToEnd();
        }               
    }
}
VB.NET
Private Sub btnOpen_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
      Dim ofd As New OpenFileDialog()
      ofd.Filter = "Text Files|*.txt"
      ofd.FilterIndex = 1
 
      If True = ofd.ShowDialog() Then
            Dim info As FileInfo = ofd.File
            Using sread As StreamReader = info.OpenText()
                  txt.Text = sread.ReadToEnd()
            End Using
      End If
End Sub
When the user runs the application now and clicks on the Open button, an Open File dialog is presented to user that allows the user browse files on their system. The user can select a text file and click on Open. For demonstration purposes, let us open the Sample.txt file as shown below:
Open
The ShowDialog() method returns true when ‘Open’ is clicked. The final step is to use the FileInfo.OpenText() to return a stream reader containing the text file contents.
The text gets displayed in the TextBox as shown below:
TextBox
Once the user has edited the text in the textbox, we will persist the changes to Sample.txt. We will use the SaveFileDialog control for this purpose.
C#
private void btnSave_Click(object sender, RoutedEventArgs e)
{
    SaveFileDialog sfd = new SaveFileDialog();
    sfd.DefaultExt = "txt";
    sfd.Filter = "Text Files (*.txt)|*.txt";
    sfd.FilterIndex = 1;
    if (true == sfd.ShowDialog())
    {
        using (Stream stream = sfd.OpenFile())
        {
            byte[] tbyte = (new UTF8Encoding(true)).GetBytes(txt.Text);
            stream.Write(tbyte, 0, tbyte.Length);
            stream.Close();
        }
    }
}
VB.NET
Private Sub btnSave_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
      Dim sfd As New SaveFileDialog()
      sfd.DefaultExt = "txt"
      sfd.Filter = "Text Files (*.txt)|*.txt"
      sfd.FilterIndex = 1
      If True = sfd.ShowDialog() Then
            Using stream As Stream = sfd.OpenFile()
                  Dim tbyte() As Byte = (New UTF8Encoding(True)).GetBytes(txt.Text)
                  stream.Write(tbyte, 0, tbyte.Length)
                  stream.Close()
            End Using
      End If
End Sub
In the code shown above, we are saving the file contents using a stream by calling the OpenFile() method.
After the user clicks on the Save button, the SaveFileDialog control is displayed.
SaveAs
All you have to do is select the existing Sample.txt file and click on Save. You can also save the file to a different file location with a different name. If you decide to overwrite the existing file, the user is prompted with the following message:
SaveAs_1
Clicking on yes overwrites the contents of the file with the contents of the textbox.

You can read more about the SaveFileDialog control over here. The entire source code of this article can be downloaded over here

If you liked the article,  Subscribe to the RSS Feed or Subscribe Via Email.

This article has been editorially reviewed by Suprotim Agarwal.

Absolutely Awesome Book on C# and .NET

C# and .NET have been around for a very long time, but their constant growth means there’s always more to learn.

We at DotNetCurry are very excited to announce The Absolutely Awesome Book on C# and .NET. This is a 500 pages concise technical eBook available in PDF, ePub (iPad), and Mobi (Kindle).

Organized around concepts, this Book aims to provide a concise, yet solid foundation in C# and .NET, covering C# 6.0, C# 7.0 and .NET Core, with chapters on the latest .NET Core 3.0, .NET Standard and C# 8.0 (final release) too. Use these concepts to deepen your existing knowledge of C# and .NET, to have a solid grasp of the latest in C# and .NET OR to crack your next .NET Interview.

Click here to Explore the Table of Contents or Download Sample Chapters!

What Others Are Reading!
Was this article worth reading? Share it with fellow developers too. Thanks!
Share on LinkedIn
Share on Google+

Author
Suprotim Agarwal, MCSD, MCAD, MCDBA, MCSE, is the founder of DotNetCurry, DNC Magazine for Developers, SQLServerCurry and DevCurry. He has also authored a couple of books 51 Recipes using jQuery with ASP.NET Controls and The Absolutely Awesome jQuery CookBook.

Suprotim has received the prestigious Microsoft MVP award for ten consecutive times. In a professional capacity, he is the CEO of A2Z Knowledge Visuals Pvt Ltd, a digital group that offers Digital Marketing and Branding services to businesses, both in a start-up and enterprise environment.

Get in touch with him on Twitter @suprotimagarwal or at LinkedIn



Page copy protected against web site content infringement 	by Copyscape




Feedback - Leave us some adulation, criticism and everything in between!
Comment posted by Uher Mutuk on Tuesday, February 2, 2010 10:46 PM
I needed this code thanks you
Comment posted by Anil patil on Tuesday, May 18, 2010 7:04 AM
thanks really...........

Categories

JOIN OUR COMMUNITY

POPULAR ARTICLES

Tags

JQUERY COOKBOOK

jQuery CookBook