OpenFileDialog в SilverLight? - PullRequest
       0

OpenFileDialog в SilverLight?

2 голосов
/ 29 апреля 2011

Я загрузил код для OpenFileDialog (функция загрузки файлов) с веб-сайта учебных пособий Silverlight. Я создаю приложение Silverlight с использованием ESRI API, и я хотел бы включить в него функцию загрузки файлов. Я реплицировал точный код в свое приложение, при его запуске ошибок нет, но по какой-то причине мое приложение не выполняет эту строку кода "c.OpenWriteAsync (Ub.Uri)"

Редактировать 2: я заметил еще одну вещь, когда я обновил общий обработчик (receive.ashx), который я скачал, и он имеет следующую строку в качестве первой строки, а мой универсальный обработчик не

<% @ WebHandler Language = "C #" Class = "получатель"%> Я не знаю, почему мой код запускает его: (

Вот мой код

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Browser;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Markup;
using System.Windows.Shapes;
using System.ComponentModel;
using ESRI.ArcGIS.Client;
using System.Windows.Controls.Primitives;
using System.IO;
using System.IO.IsolatedStorage;


namespace DataTool
{
  public partial class MainPage : UserControl
  {
  public MainPage()
  {
  InitializeComponent();
  Loaded += new RoutedEventHandler(MainPage_Loaded);
  }

  void MainPage_Loaded(object sender, RoutedEventArgs e)
  {
   // HtmlPage.RegisterScriptableObject("SilverlightLearn", this);
  }

  [ScriptableMember]
  private void btnService_Click(object sender, RoutedEventArgs e)
  {
  }

  private void btnUpload_Click(object sender, RoutedEventArgs e)
  {
  OpenFileDialog Dialog = new OpenFileDialog();
  Dialog.Multiselect = false;
  Dialog.Filter = "All Files|*.*";

  bool? SelFil = Dialog.ShowDialog();

  if (SelFil != null && SelFil == true)
  {
  string selectedfilename = Dialog.File.Name;
  UploadFile(selectedfilename, Dialog.File.OpenRead());

  }
  else
  {
  //do something else
  }
  }
  private void StoreIso(string fileName, Stream data)
  {

  }

  private void UploadFile(string fileName, System.IO.Stream data)
  {
   // WebClient Wbc = new WebClient();
  UriBuilder Ub = new UriBuilder("http://localhost:63461/DataTool/datareceiver.ashx");
  Ub.Query = string.Format("filename={0}", fileName);

  WebClient c = new WebClient();
  c.OpenWriteCompleted += (sender, e) =>
  {
  PushData(data, e.Result);
  e.Result.Close();
  data.Close();
  };
  c.OpenWriteAsync(Ub.Uri);
  }
  private void PushData(Stream input, Stream output)
  {

  byte[] buffer = new byte[4096];
  int bytesRead;

  while ((bytesRead = input.Read(buffer, 0, buffer.Length)) != 0)
  {
  output.Write(buffer, 0, bytesRead);
  }

  }

  }
}

Вот мой код datareceiver.ashx

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;

namespace DataTool.Web
{
  /// <summary>
  /// Summary description for datareceiver
  /// </summary>
  public class datareceiver : IHttpHandler
  {

  public void ProcessRequest(HttpContext context)
  {
  string filename = context.Request.QueryString["filename"].ToString();

  using (FileStream fs = File.Create(context.Server.MapPath("~/App_Data/" + filename)))
  {
  SaveFile(context.Request.InputStream, fs);
  }

  }
  public void SaveFile(Stream st, FileStream fs)
  {
  byte[] buffer = new byte[4096];
  int bytesRead;

  while ((bytesRead = st.Read(buffer, 0, buffer.Length)) != 0)
  {
  fs.Write(buffer, 0, bytesRead);
  }
  }

  public bool IsReusable
  {
  get
  {
  return false;
  }
  }
  }
}

Я просмотрел загруженный пример кода и мой код STEP BY STEP и обнаружил, что мой код не выполняет инструкцию OpenWriteAsync. Загруженный код был в .net 3.5 или 3.0 framework, и я обновил его до 4.0.

EDIT: Пожалуйста, найдите образец здесь https://rapidshare.com/files/459667631/Testing.zip

1 Ответ

1 голос
/ 29 апреля 2011

Это просто, проверьте следующий код

OpenFileDialog dlg = new OpenFileDialog();
dlg.Filter = "Text Files (*.txt)|*.txt";
if (dlg.ShowDialog() == DialogResult.OK)
{
    using (StreamReader reader = dlg.SelectedFile.OpenText())

        // Store file content in 'text' variable
        string text = reader.ReadToEnd();
    }
}


C# Example 2: Copy files to the application's isolated storage.  
using System.Windows.Controls;
using System.IO;
using System.IO.IsolatedStorage;
...

OpenFileDialog dlg = new OpenFileDialog();
dlg.Filter = "All files (*.*)|*.*";
dlg.EnableMultipleSelection = true;
if (dlg.ShowDialog() == DialogResult.OK) {
    // Save all selected files into application's isolated storage
    IsolatedStorageFile iso = IsolatedStorageFile.GetUserStoreForApplication();
    foreach (FileDialogFileInfo file in dlg.SelectedFiles) {
        using (Stream fileStream = file.OpenRead()) {
            using (IsolatedStorageFileStream isoStream =
                new IsolatedStorageFileStream(file.Name, FileMode.Create, iso)) {

                // Read and write the data block by block until finish
                while(true) {
                    byte[] buffer = new byte[100001];
                    int count = fileStream.Read(buffer, 0, buffer.Length);
                    if (count > 0) {
                        isoStream.Write(buffer, 0, count);
                    }
                    else {
                        break;
                    }
                }
            }
         }
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...