I made a Silverlight application that captures image using the web cam. The application works perfectly however when I save the captured image it 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) in System.IO.FileStream..ctor (String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost ) in System.IO.FileStream..ctor (String path, FileMode mode, FileAccess access, FileShare> share) in SilverlightCam.WebCam.SaveImage (FrameworkElement bitmap) in SilverlightCam.MainPage.BtSalvar_Click (Object sender, RoutedEventArgs e)
The D: \ Web folder contains all the permissions and when I run the application out of the browser I can save it to the folder without any 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 an Image component where I store the captured image. Any help is welcome