Access Denied when saving image to an application

Asked

Viewed 783 times

3

I made a Silverlight app that captures image using web cam. The application works perfectly however when I save the captured image generates the following error:

File Operation not permitted. Access to path: ’D: Web.... ' is denied

Stack Trace:

in System.IO.Filesecuritystate.Ensurestate() in System.IO.Filestream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost) em System.IO.FileStream.. ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost) em System.IO.FileStream.. ctor(String path, FileMode mode, FileAccess access, FileShare >share) em SilverlightCam.WebCam.SalvarImagem(FrameworkElement bitmap) em SilverlightCam.MainPage.BtSalvar_Click(Object sender, RoutedEventArgs e)

The D: Web folder contains all permissions and even when I run the application outside the browser (Out-of-browser) I can save it to the folder without problems.

The method that saves the image is this:

public void SalvarImagem(FrameworkElement bitmap)
{            
 String filename = @"D:\Web\" + MakeFileName();
 using (FileStream stream = new FileStream(filename, FileMode.Create,   FileAccess.Write, FileShare.Write))
 {                
   BitmapSource source = GetBitmapSource(bitmap);
   PngBitmapEncoder encoder = new PngBitmapEncoder();

   encoder.Frames.Add(BitmapFrame.Create(source));
   encoder.Save(stream);
   stream.Close();                
 }            
}

The 'Makefilename' method generates a random name for the image to be saved:

internal static String MakeFileName()
{
  int index = 0;
  bool uppercase = false;
  String filename = String.Empty;
  String caracters = "abcdefghijklmnopqrstuvwxyz1234567890";

  Random random = new Random();

  for (int i = 0; i < caracters.Length; i++)
  {
   uppercase = Convert.ToBoolean(random.Next(0, 2));                
   index = random.Next(0, caracters.Length);

   filename += uppercase == true ? Char.ToUpper(caracters[index]) : caracters[index];                
  }    

 return String.Format("{0}.{1}", filename, "png");
}

In turn the 'Getbitmapsource' method renders the image in the component:

internal static BitmapSource GetBitmapSource(FrameworkElement element)
{
 ScaleTransform scale = new ScaleTransform() { ScaleX = 1, ScaleY = 1 };            
 Size size = new Size(element.ActualWidth, element.ActualHeight);

 WriteableBitmap bitmap = new WriteableBitmap((int)size.Width, (int)size.Height);
 bitmap.Render((element as UIElement), scale);
 bitmap.Invalidate();

 return (bitmap as BitmapSource);
}

I call the function as follows:

private void BtSalvar_Click(object sender, RoutedEventArgs e)
{
 try
 {
  WebCam.SalvarImagem(ImageCam);
  lblMsg.Content = "Imagem Salva com Sucesso!";
 }

 catch (Exception ex)
 {
  lblMsg.Content = ex.Message;
  txtLog.Text = ex.StackTrace;
 }
}

Imagecam is a component Image where I store the captured image. Any help is welcome

  • I thought the tag Silverlight would never be created :) A tip since you like to capture Exception: http://answall.com/questions/30124/h%C3%A1-some-inconvenient-in-always-capture-Exception-e-n%C3%A3o-something-more-spec%C3%Adfico/30168#30168 will follow the links, it is full of posts on the subject.

  • Interesting article, I used a 'generic' Exception for not knowing how to capture the generated error. Since I came from Java I got used to Netbeans/Eclipse telling me what exception.

1 answer

4


You cannot access the local file system in a Silverlight application directly - if that were the case, a site could have a Silverlight control hidden in a page, and would have access to the file system of anyone who visited the site. To access the file system, the user needs to give permission to the SL application for such, and this can be done in two ways;

  • Unstalar the application locally: by doing this the user indicates that "trust" the application
  • Use a SaveFileDialog, where the user has to choose which file will be recorded.

The code below shows a way to implement the second option:

public void SalvarImagem(FrameworkElement bitmap)
{
    SaveFileDialog sfd = new SaveFileDialog();
    sfd.Filter = "Arquivos PNG|*.png|Todos os arquivos|*.*";
    sfd.DefaultExt = ".png";
    var result =sfd.ShowDialog();
    if (result.HasValue && result.Value) {
        using (stream = sfd.OpenFile())
        {                
            BitmapSource source = GetBitmapSource(bitmap);
            PngBitmapEncoder encoder = new PngBitmapEncoder();

            encoder.Frames.Add(BitmapFrame.Create(source));
            encoder.Save(stream);
            stream.Close();                
        }            
    }
}
  • Thank you so much! It worked here. Now as I would to install the application locally?

  • Install locally = run out of the browser (out of browser), which you have already managed to do, according to your question.

  • I get it. I’m still a beginner in the world of Silverlight

Browser other questions tagged

You are not signed in. Login or sign up in order to post.