Search code examples
silverlightopenfiledialog

OpenFileDialog Silverlight


I have no problems with using of OpenFileDialog (in Windows Forms). I can not understand for sure where the error using OpenFileDialog in Silverlight( WPF). In my code I am interested by this string , where it necessary to show the path:

var lines = File.ReadLines(fileStream);

all code for Silverlight (does not work):

        private void Button_Click(object sender, RoutedEventArgs e)
    {

        OpenFileDialog opendialog = new OpenFileDialog();
        System.IO.Stream fileStream = opendialog.File.OpenRead();
        if (opendialog.ShowDialog() == true)
        {
            var lines = File.ReadLines(fileStream); 
            string pattern = @"set vrouter ""([\w-]+)""";

            var matches =
                lines.SelectMany(line => Regex.Matches(line, pattern)
                    .Cast<Match>()).Where(m => m.Success)
                    .Select(m => m.Groups[1].Value)
                    .Distinct();

            foreach (String match in matches)
            {

                textBox1.AppendText(match + Environment.NewLine);
            }
        }
    }
}

}

Code for Windows Forms (works well):

        private void button1_Click(object sender, EventArgs e)
    {
        OpenFileDialog opendialog = new OpenFileDialog();
        if (opendialog.ShowDialog() == DialogResult.OK)
        {
            var lines = File.ReadLines(opendialog.FileName);
            string pattern = @"set vrouter ""([\w-]+)""";

                var matches = 
                    lines.SelectMany(line=> Regex.Matches(line, pattern)
                        .Cast<Match>()).Where(m => m.Success)
                        .Select(m => m.Groups[1].Value)
                        .Distinct();

                foreach (String match in matches)
                {

                        textBox1.AppendText(match + Environment.NewLine);
                }
            }



    }

Solution

  • Silverlight runs with elevated permissions by default(simply saying in sandbox), it means

    var lines = File.ReadLines(fileStream);
    

    wil not work, for 2 reasons:

    1. parameter should be string path, not a stream in silverlight api, at least.
    2. File.ReadLines will not work, because it works only for trusted applications.

    based on above, your issue can be solved by following code:

    OpenFileDialog opendialog = new OpenFileDialog();
    if (opendialog.ShowDialog() == true)
    {
       string text = string.Empty;
       using (StreamReader reader = opendialog.File.OpenText()) 
       {
       text = reader.ReadToEnd();
       }
       // do stuff here
    }
    

    or another options provided by msdn : http://msdn.microsoft.com/en-us/library/cc221415(v=vs.95).aspx