Silverlight 3 瀏覽器端儲存檔案

Silverlight 3 中新增的一項小功能,讓瀏覽器端儲存檔案,比起以前容易多了,但考量安全問題,必須透過使用者操作對話方塊形式,選取欲寫入的資料夾後,才可寫入檔案,開發人員仍不允許自由決定資料夾位置。

using System.IO;
using System.Text;

private void btnSaveFile_Click(object sender, RoutedEventArgs e)
{
           string myTextFile = "要儲存之檔案內容";

           SaveFileDialog dlg = new SaveFileDialog();
           dlg.DefaultExt = "txt";
           dlg.Filter = "文字文件(*.txt)|*.txt|所有檔案(*.*)|*.*";
           dlg.FilterIndex  = 1;
           if (dlg.ShowDialog() == true)
           {               
               using (Stream stream = dlg.OpenFile())
               {
                    byte[] fileByte = (new UTF8Encoding(true)).GetBytes(myTextFile);
                   stream.Write(fileByte, 0, fileByte.Length);
                   stream.Close();
               }
}

只需短短幾行程式碼即可完成,與 Silverlight 2 時相較真是宛如隔世。

Silverlight3SaveFile.zip