使用OpenFileDialog(在Windows窗体中)没有问题。 我无法确定在Silverlight(WPF)中使用OpenFileDialog时出错的位置。在我的代码中,我对此字符串感兴趣,需要显示路径:
var lines = File.ReadLines(fileStream);
Silverlight的所有代码(不起作用):
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);
}
}
}
}
}
Windows窗体代码(运行良好):
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);
}
}
}
答案 0 :(得分:1)
默认情况下,Silverlight以提升权限运行(简单地说在沙箱中),这意味着
var lines = File.ReadLines(fileStream);
将无法工作,原因有两个:
基于以上所述,您可以通过以下代码解决您的问题:
OpenFileDialog opendialog = new OpenFileDialog();
if (opendialog.ShowDialog() == true)
{
string text = string.Empty;
using (StreamReader reader = opendialog.File.OpenText())
{
text = reader.ReadToEnd();
}
// do stuff here
}
或msdn提供的其他选项:http://msdn.microsoft.com/en-us/library/cc221415(v=vs.95).aspx
答案 1 :(得分:0)
private void Button_Click(object sender, EventArgs e)
{
OpenFileDialog opendialog = new OpenFileDialog();
opendialog.Multiselect = true;
bool? dialogResult = opendialog.ShowDialog();
if (dialogResult.HasValue && dialogResult.Value)
{
textBox1.Text = string.Empty;
foreach (var file in opendialog.Files)
{
Stream fileStream = file.OpenRead();
using (StreamReader reader = new StreamReader(fileStream))
{
string pattern = @"set vrouter ""([\w-]+)""";
while (!reader.EndOfStream)
{
var matches =
Regex.Matches(reader.ReadToEnd(), pattern)
.Cast<Match>().Where(m => m.Success)
.Select(m => m.Groups[1].Value)
.Distinct();
foreach (var match in matches)
{
textBox1.Text += val;
}