## Reading and writing local files in Silverlight/C#

In a Silverlight app running in a web page, it’s possible to read and write local files with one restriction: the end-user needs to select the files. The following code is an ultra-simple example of how it’s done.

LocalFileReadWrite is very simple web app that displays a TextBox and two Buttons, Save and Open. Clicking the Open button allows you to open a *.txt and display it in the TextBox. You can then edit the text, click Save to save the contents of the TextBox into another file. It’s a bit like Notepad.exe, but with even fewer features 😉

You can try it here.

A zip of the whole project can be found here. It’s buildable with MS Visual Web Developer 2010 Express. Most of it’s boilerplate stuff you get when you create a new project. The only files I modified were the C# file MainPage.xaml.cs and the XAML file MainPage.xaml.

I was pleasantly surprised at how little code was required. It’s even less complicated than reading/writing local files in Flash (see Mike Chambers’ post on that).

Here’s the C# code:

using System;
using System.Windows;
using System.Windows.Controls;
using System.Diagnostics;		// Debug.WriteLine
using System.Text;				// UTF8Encoding
using System.IO;				// Stream, IOStream

{
public partial class MainPage : UserControl
{
private const String FILE_FILTER = "Text files (*.txt)|*.txt";
private const String WELCOME = "Type text here. Click 'Open' to open any *.txt file. Click 'Save' to save to a new *.txt file (or overwrite an existing one).";

public MainPage()
{
InitializeComponent();
textBox.Text = WELCOME;
}

private void OnOpenButtonClick(object sender, RoutedEventArgs e)
{
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.Filter = FILE_FILTER;

if (openFileDialog.ShowDialog() == true)
{
byte[] textBytes = new byte[fileStream.Length];
textBox.Text = UTF8Encoding.UTF8.GetString(textBytes, 0, textBytes.Length);
}
}

private void OnSaveButtonClick(object sender, RoutedEventArgs e)
{
SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.Filter = FILE_FILTER;

if (saveFileDialog.ShowDialog() == true)
{
System.IO.Stream stream = saveFileDialog.OpenFile();
byte[] textBytes = UTF8Encoding.UTF8.GetBytes(textBox.Text);
stream.Write(textBytes, 0, textBytes.Length);
stream.Close();
}
}
}
}


And here’s the XAML:

<UserControl x:Class="LocalFileReadWrite.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:DesignHeight="380" d:DesignWidth="696">

<Grid x:Name="LayoutRoot" Background="White">
<Button Content="Open" Height="23" HorizontalAlignment="Left" Margin="12,12,0,0" Name="openButton" VerticalAlignment="Top" Width="75" Click="OnOpenButtonClick" />
<Button Content="Save" Height="23" HorizontalAlignment="Left" Margin="93,12,0,0" Name="saveButton" VerticalAlignment="Top" Width="75" Click="OnSaveButtonClick" />
<TextBox Margin="12,41,12,12" Name="textBox" TextWrapping="Wrap" VerticalScrollBarVisibility="Auto" AcceptsReturn="True" />
</Grid>
</UserControl>


Reading and writing text files is of course just one thing you can do given the ability to read/write local files. One can imagine creating all sorts of handy web-based utilities – hex editors, waveform editors, image editors – all running in web pages, and accessible from Mac or PC.

Feel free to use and modify the code as you wish, though some sort of attribution (a link or comment in the code) is always appreciated. Enjoy!

I'm a Singapore-based Canadian software engineer, inventor, musician, and occasional triathlete. My current work and projects mainly involve audio technology for the web and iOS. I'm the author of AudioStretch, an audio time-stretching/pitch-shifting app for musicians. Past jobs have included writing speech recognition software for Apple, creating automatic video editing software for muvee, and designing ASICs for Nortel. I hold a Bachelor of Applied Science (Electrical Engineering) from Queen's University and a Master of Arts in Electroacoustic Music from Dartmouth College.
This entry was posted in Programming. Bookmark the permalink.

### 20 Responses to Reading and writing local files in Silverlight/C#

1. THXTOYOU says:

hi, thx for your output Gerry. May the force be with you!

2. Brian Wendt says:

Excellent tutorial. How do I do the same with a file that is not in UTF8 encoding?

• If you’re dealing with raw binary (not text) data, System.IO.FileStream.Read() and System.IO.Stream.Write() should do the trick. That’s what I use in my example; to convert the byte data to/from string format, I use the UTF8Encoding class. If you’re dealing with text but it’s not in UTF8 format, you might try other text encoding classes in System.text, such as UnicodeEncoding, UTF7Encoding, UTF32Encoding.

• Brian Wendt says:

Thank you for the suggestion. I ended up doing the following:

if (ofd.ShowDialog() == true)
{
{
int i = 0;
string line;
while ((line = tr.ReadLine()) != null)
{

3. Incidentally, on a Mac, hitting backspace while you’re entering text in the text box causes the browser to navigate to the previous page. I never noticed this before, so I’m guessing it’s new with Mac OS Lion. Someone else already logged the issue (and a workaround) with Microsoft here:
https://connect.microsoft.com/VisualStudio/feedback/details/717056/silverlight-4-5-backspace-issue-on-safari-5-mac-lion

4. Amit Tandon says:

Well done!! Very nice article I really enjoyed it during reading this article. It helped me lot and cleared lot of my doubts in Silverlight file handling. Some good articles also explained very well about read and write file in silverlight which, url of these posts….

Thanks Everyone!!!

Hi,
Nice article. Can we read a file content(stored in client PC) from java script. i need to read a file always the same file because the users are in house users so we will definitely have a file called c:\text.txt. i need to read this file and populate the drop down in the client side javascript. is this possible? Please let me know your suggestion. thanks.

• With HTML5 you definitely can read local files in Javascript. As is the case with reading local files in ActionScript/Flash or C#/Silverlight, the local file must be selected by the user (e.g. by clicking a button to bring up a dialog to choose a file).

6. Gerry,

Thanks for the article. Very good one.

However, I’m trying to write to a file present alongside the HTML file hosting the silverlight XAP. Currently, I get an access denied exception. Could you suggest a way to do this?

• Thanks for reading! Offhand I really have no idea… but judging from the number of hits for a Google search on “Silverlight Permission denied server writing file”, a lot of people have run into the same problem!

• Thanks for your response! To put my actual requirement: All I’m trying to do is to log or keep track of visitor count from a silverlight application hosted on a server. Since the server owner does not provide me a database, writing to a file was the best bet.

Any inputs to accomplish this?

• I’ve done something like that in ActionScript, so I’d be surprised if it wasn’t possible to do with Silverlight. Alternatively you could use a bit of PHP code in your HTML; PHP can definitely write to files on the server.

• Gerry, Thanks for your suggestion – it helped! 🙂

7. Jonathan says:

Gary,

Thank you for this, how would you do this with an excel file?

• You’d need to change the FILE_FILTER so that it lists the types of Excel files you want to be able to open (e.g. *.csv, *.xls). Info on the OpenFileDialog’s FileFilter property can be found here:
http://msdn.microsoft.com/en-us/library/system.windows.forms.filedialog.filter.aspx

A CSV (“Comma-Separated Values”) would be pretty easy to deal with – it’s basically just a plain text file with values separated by commas. As for XLS, there’s probably some C# library that you could use in Silverlight. I don’t know offhand what library would be good, but a Google search for “C# Excel parsing” gives about 47 million (!?) results.

8. André says:

It’s exactly what I was searching since a couple of hours. I at last found an article about files!
An excellent one.

Thanks a lot Monsieur Beauregard.
D’un programmeur du Québec.

Glad to hear it was useful! -Gérald (un franglophone d’origine de Montréal)

9. splintor says:

Thanks for this post. In your test page, I noticed that when I save and select an existing file, Silverlight ask if I want to replace it. Clicking Yes dismiss the save dialog, but the content is not saved to the file. Is this a known problem? I’m using Chrome and Silverlight 5.1.20125.0.

• I really don’t know… haven’t looked at Silverlight in ages. The test page still works OK for me with Safari on my Mac, and saving over an existing file seems to be OK too. In Chrome (with Silverlight 5.1.10411.0) I notice I can’t even type any text at all, but I can select and delete the default text. Very strange!

10. Audrea says: